PHP Preg_replace替换数组

时间:2011-12-23 01:46:51

标签: php preg-replace anonymous-function preg-replace-callback

好的,我正在尝试这样做:

preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);

现在我知道这是不可能的,但是我想知道是否有办法做到这一点,因为我曾尝试使用create_function但是,$ templateVariables是函数的局部变量,它是在内部,所以我无法从create_function中访问$ templateVariables,所以我有点卡在这里。我宁愿不必找到匹配找出替换它们的内容,然后再次找到它们来替换,这看起来很可怕效率低下。那么无论如何我可以从匿名函数中获取局部变量,或者任何人都有任何好的建议。

感谢。

3 个答案:

答案 0 :(得分:4)

试试这个:

$vars = array(
    "test" => "Merry Christmas",
);
$string = "test {test} test";
$string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
    return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
}, $string);
echo $string;

应输出:

  

测试圣诞快乐测试

您可以在此处查看一个有效的示例http://codepad.viper-7.com/2ZNNYZ

答案 1 :(得分:-1)

您实际上可以将preg_replace与/ e修饰符一起使用:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", '$templateVariables[\'$1\']', $templateString)

但这可能不是最安全的方式......

答案 2 :(得分:-1)

您需要使用e regexp修饰符:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", "\$templateVariables['\\1']", $templateString);