首页 > 解决方案 > 如何用 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]')";

但它仍然不起作用。

谢谢您的帮助。

标签: phpphp-5.6preg-replace-callback

解决方案


最后,它适用于以下代码:

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。

最好的。


推荐阅读