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

标签 php regex preg-replace

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

$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!

参见 the docs for the modifier 'e' .

关于PHP preg_replace - 使用匹配项作为键从数组中查找替换项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3237267/

相关文章:

类似于此 JavaScript 函数的 PHP 函数

php - 如何使用preg_replace和htaccess修改url?

php - 将嵌套文本转换为字符串

php - PHP 检测文件是否完整或部分

php - 为什么这个递归函数会这样工作?

java.util.regex.PatternSyntaxException : Dangling meta character '+' near index 0 +

javascript - RegEX 用于解析和循环多个自定义标签

ruby - 正则表达式错误 : too many multibyte code ranges are specified

php - C for 循环与 PHP for 循环不同吗?

php - 跨多个请求使用 Zend session 命名空间