PHP preg_replace - 使用匹配作为键从数组中查找替换

aar*_*ell 6 php regex preg-replace

我有一个字符串,可以包含多个匹配(由百分比标记包围的任何单词)和一个替换数组 - 每个替换的键是正则表达式的匹配.有些代码可能会更好地解释......

$str = "PHP %foo% my %bar% in!";
$rep = array(
  'foo' => 'does',
  'bar' => 'head'
);
Run Code Online (Sandbox Code Playgroud)

期望的结果是:

$str = "PHP does my head in!"
Run Code Online (Sandbox Code Playgroud)

我尝试了以下,没有一个工作:

$res = preg_replace('/\%([a-z_]+)\%/', $rep[$1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['$1'], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep[\1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['\1'], $str);
Run Code Online (Sandbox Code Playgroud)

因此,我转向Stack Overflow寻求帮助.任何接受者?

Art*_*cto 7

echo preg_replace('/%([a-z_]+)%/e', '$rep["$1"]', $str);
Run Code Online (Sandbox Code Playgroud)

得到:

PHP does my head in!

请参阅修饰符"e"的文档.

  • 自PHP 5.5以来,'e'修饰符被"弃用并且非常不鼓励使用".根据这个答案中引用的文档.使用preg_replace_callback()的替代解决方案[此处](http://stackoverflow.com/questions/16237882/preg-replace-using-pattern-as-index-of-replacement-data-array) (3认同)