PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何使用preg_replace_callback()改写这个函数?

原创
2016-06-06 20:46:22 849浏览

最近的项目,在更新完PHP以后发现preg_replace()在5.5.0版本起/e修饰符已经被弃用了。然后不知道怎么改写

$source_content = preg_replace($search.'e', "'"
                                       . $this->_quote_replace($this->left_delimiter) . 'php'
                                       . "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'"
                                       . $this->_quote_replace($this->right_delimiter)
                                       . "'"
                                       , $source_content);

求大神指教

回复内容:

最近的项目,在更新完PHP以后发现preg_replace()在5.5.0版本起/e修饰符已经被弃用了。然后不知道怎么改写

$source_content = preg_replace($search.'e', "'"
                                       . $this->_quote_replace($this->left_delimiter) . 'php'
                                       . "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'"
                                       . $this->_quote_replace($this->right_delimiter)
                                       . "'"
                                       , $source_content);

求大神指教

preg_replace()/e模式被废弃了,不是preg_replace()被废弃了好么!!请不要以偏概全的说话!!搞得我一开始都吓尿了,还以为PHP特么怎么这么随便呢。

preg_replace_callback()不是很简单么,就是用函数替换了用eval执行字符串啊。不过说老实话没怎么看明白你的替换执行函数到底要干嘛,好像是要根据换行符的个数重新写一遍换行??写个参考给你吧:

$source_content = preg_replace_callback($search, function($matches) {
    return str_repeat("\n", substr_count($matches[0], "\n");
}, $cource_content);

函数的$matches参数就是你的$search匹配得到的结果,如果还是不懂还是看看手册吧,手册上已经写的很全了。

这里是smarty官方给出的答案:
$source_content = preg_replace_callback($search, create_function ('$matches', "return '"
. $this->_quote_replace($this->left_delimiter) . 'php'
. "' . str_repeat(\"\n\", substr_count('\$matches[1]', \"\n\")) .'"
. $this->_quote_replace($this->right_delimiter)
. "';") , $source_content);

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。