将文本中的变量替换为相应的值

时间:2015-12-01 12:07:31

标签: php regex replace preg-replace preg-match

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

"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是一个带有值的数组,但我需要用值为

的数组中的相应值替换每个匹配项

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

3 个答案:

答案 0 :(得分:3)

您可以使用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]指的是(.*?)捕获的内容。我想这种模式对于当前场景是足够的(不需要展开,因为它匹配的字符串相对较短)。

答案 1 :(得分: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);

答案 2 :(得分:1)

尝试

<?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;
相关问题