我有一个字符串,它可以包含多个匹配项(任何由百分比标记包围的单词)和一个替换数组 - 每个替换项的键是正则表达式的匹配项。一些代码可能会更好地解释......
$str = "PHP %foo% my %bar% in!";
$rep = array(
'foo' => 'does',
'bar' => 'head'
);
期望的结果是:
$str = "PHP does my head in!"
我尝试了以下方法,但均无效:
$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);
因此我求助于 Stack Overflow。有没有人要?
最佳答案
echo preg_replace('/%([a-z_]+)%/e', '$rep["$1"]', $str);
给出:
PHP does my head in!
关于PHP preg_replace - 使用匹配项作为键从数组中查找替换项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3237267/