如何使用preg_replace_callback替换此preg_replace以实现php 5.6兼容性

时间:2019-05-07 09:39:47

标签: php php-5.6 preg-replace-callback

我正在尝试更新20岁的某些代码以与php 5.6兼容。我面临的主要变化之一是在preg_replace中弃用了“ / e”修饰符。

对于大多数情况,我只是将其替换为preg_replace_callback,删除了“ / e”并使用了一个函数作为第二个arg。

但是我面临着无法正常工作的情况,在尝试了许多尝试之后,我仍然无法重现以前的工作方式。

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]')";

但是它仍然不起作用。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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。

非常感谢wiktorstribiżew。您的代码更好,但第二部分不受/ e的关注,因此我改回了preg_replace。

最好。