duanjing4623 2015-12-01 12:07
浏览 105
已采纳

用相应的值替换文本中的变量

Let say I have the following string which I want to send as an email to a customer.

"Hello Mr/Mrs {{Name}}. You have subscribed for {{Service}} at {{Date}}."

And I have an array with the values that should be replaced

array(
    'Name' => $customerName, //or string
    'Service' => $serviceName, //or string
    'Date' => '2015-06-06'
);

I can find all strings between {{..}} with this:

preg_match_all('/\{{(.*?)\}}/',$a,$match);

where $match is an array with values, But I need to replace every match with a corresponding value from an array with values

Note that the array with values contains a lot more values and the number of items in it or the keys sequence is not relevant to number of matches in string.

  • 写回答

3条回答 默认 最新

  • draw62188 2015-12-01 12:10
    关注

    You can use preg_replace_callback and pass the array with the help of use to the callback function:

    $s = "Hello Mr/Mrs {{Name}}. You have subscribed for {{Service}} at {{Date}} {{I_DONT_KNOW_IT}}.";
    $arr = array(
        'Name' => "customerName", //or string
        'Service' => "serviceName", //or string
        'Date' => '2015-06-06'
    );
    echo $res = preg_replace_callback('/{{(.*?)}}/', function($m) use ($arr) {
           return isset($arr[$m[1]]) ? $arr[$m[1]] : $m[0]; // If the key is uknown, just use the match value
        }, $s);
    // => Hello Mr/Mrs customerName. You have subscribed for serviceName at 2015-06-06.
    

    See IDEONE demo.

    The $m[1] refers to what has been captured by the (.*?). I guess this pattern is sufficient for the current scenario (does not need unrolling as the strings it matches are relatively short).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?