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条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器