从preg_replace转换为preg_replace_callback

时间:2017-09-19 16:15:45

标签: php php-7

很抱歉重复这个问题,但我有个案使用preg_replace函数。这是将模板($ data)中的变量($ vars)从其名称替换为其值

的函数
function replace_vars($data, array $vars) {
    return preg_replace(array('/\{\{([a-zA-Z0-9_]+)\}\}/e', '/\{\{([a-zA-Z0-9_]+):(\d+)\}\}/e'),
        array("\$vars['\\1']", "\$vars['\\1'][\\2]"), $data);
}

$ template fragment

<td>{{name}}</td>
<td>{{active_items}}</td>
<td>{{percents}} %</td>

函数调用

$report = '';
$f['name'] = 'some name';
$f['active_items'] = 237;
$f['percents'] = 'some name';
$report .= $mailer->replace_vars($template, $f);

我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果我理解你,那很简单。

preg_replace_callback([...], function($matches) use ($vars) {
  # Use ($vars) will inherit it from the current scope
  $v = $vars[$matches[1]]; # Select item with key of capturing group 1
  if ($matches[2]) { # If group 2 was matched
    $v = $v[$matches[2]]; # Select contents of item with the same key as it's value from the previous item
  }
  return $v; # Replace it.
}, [...]);

如果第2组匹配,它将用$var[\1]$var[\1][\2]替换所有匹配。