假设我有以下字符串,我想将其作为电子邮件发送给客户。
"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]
指的是 (.*?)
捕获的内容。我想这个模式足以满足当前场景(不需要展开,因为它匹配的字符串相对较短)。
关于php - 将文本中的变量替换为相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020100/