php - 如何用 preg_replace_callback 替换这个 preg_replace 以实现 php 5.6 兼容性
问题描述
我正在尝试更新一些 20 年前的代码以与 php 5.6 兼容。我面临的主要变化之一是 preg_replace 中“/e”修饰符的弃用。
对于他们中的大多数人,我只是将其替换为 preg_replace_callback,删除了“/e”并使用了一个函数作为第二个参数。
但我面临一个它不起作用的情况,经过很多尝试,我仍然无法重现它之前的工作方式。
function _munge_input($template) {
$orig[] = '/<\?plugin.*?\?>/se';
$repl[] = "\$this->_mungePlugin('\\0')";
$orig[] = '/<\?=(.*?)\?>/s';
$repl[] = '<?php $this->_print(\1);?>';
return preg_replace($orig, $repl, $template);
}
我试图将 $repl 替换为:
function ($matches) use ($repl) {
return $repl;
}
(甚至直接在函数中包含 $repl 赋值)
修改了第一个 $repl 分配:
$repl[] = "\$this->_mungePlugin('$matches[0]')";
但它仍然不起作用。
谢谢您的帮助。
解决方案
最后,它适用于以下代码:
function _munge_input($template) {
$that = $this;
$template = preg_replace_callback(
'/<\?plugin.*?\?>/s',
function ($matches) use ($that) {
return $that->_mungePlugin($matches[0]);
},
$template
);
$template = preg_replace('/<\?=(.*?)\?>/s', '<?php $this->_print(\1);?>', $template);
return $template;
}
正如您告诉我的那样,问题是在另一个范围内使用 $this 。
非常感谢wiktor stribiżew。您的代码更好,但第二部分与 /e 无关,所以我改回 preg_replace。
最好的。
推荐阅读
- php - 在简短描述产品 WooCommerce 中显示带有价格的自定义文本
- javascript - 如何拦截非 JSON 的响应
- animation - 无法更改unity3D中的动画帧数
- javascript - 类似于 map 的 ES6 函数
- r - knitr sanitize_fn 警告通过 knit2pdf 将绘图合并到乳胶中
- linux - localhost 在 Docker 容器中是什么意思?
- mailkit - MessageSummaryItems.PreviewText 澄清
- javascript - 在什么情况下,我必须在语句的末尾加上分号?
- webpack - 在 webpack 的摇树中包含 sourcemap
- plugins - 材质主题编辑器插件未打开