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

Replace variables from text with corresponding values

假设我有以下字符串,我想将其作为电子邮件发送给客户。

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

我有一个包含应替换值的数组

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

我可以找到 {{..}} 之间的所有字符串:

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

其中 $match 是一个包含值的数组,但我需要用一个包含值的数组中的相应值替换每个匹配项

请注意,带有值的数组包含更多的值,其中的项目数或键序列与字符串中的匹配数无关。

您可以使用 preg_replace_callback 并在 use 的帮助下将数组传递给回调函数:

$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.

IDEONE demo

$m[1]指的是被(.*?)捕获的内容。我想这个模式对于当前场景已经足够了(不需要展开,因为它匹配的字符串相对较短)。

你不需要为此使用正则表达式,如果你稍微改变数组键,你可以用一个简单的替换函数来做到这一点:

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

$new_keys = array_map(function($i) { return '{{' . $i . '}}';}, array_keys($corr));
$trans = array_combine($new_keys, $corr);

$result = strtr($yourstring, $trans);

尝试

<?php

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

$arr = array(
    'Name' => 'some Cust', //or string
    'Service' => 'Some Service', //or string
    'Date' => '2015-06-06'
);

$replaceKeys = array_map(
   function ($el) {
      return "{{{$el}}}";
   },
   array_keys($arr)
);

$str = str_replace($replaceKeys, array_values($arr), $str);

echo $str;