php7中,preg_replace()不再支持"\e" (PREG_REPLACE_EVAL),需要使用preg_replace_callback()来代替。
比如下面的代码在php7是不行的。
$out = "<?php \n" . '$k = ' . preg_replace("/(\'\\$[^,]+)/e", "stripslashes(trim('\\1','\''));", var_export($t, true)) . ";\n";
需要使用preg_replace_callback函数改造下。
$out = "<?php \n" . '$k = ' . preg_replace_callback("/(\'\\$[^,]+)/", function ($matches) {
return stripslashes(trim($matches[0], '\''));
},
var_export($t, true)) . ";\n";
如果在回调函数中要使用类的方法
class Template {
function fetch_str($source)
{
return preg_replace("/{([^\}\{\n]*)}/e", "\$this->select('\\1');", $source);
}
public function select($tag)
{
return stripslashes(trim($tag));
}
}
则需要改造成下面的形式。
class Template {
function fetch_str($source)
{
return preg_replace_callback("/{([^\}\{\n]*)}/", [$this, 'select'], $source);
}
public function select($tag)
{
return stripslashes(trim($tag[1]));
}
}
本文介绍在PHP7中如何正确使用preg_replace()函数,并提供了将e替换为preg_replace_callback()的具体示例代码。此外还展示了如何在回调函数中调用类的方法。
468

被折叠的 条评论
为什么被折叠?



