从php5.2.6迁移后,/e修饰符已被弃用,请使用preg_replace_callback。

3

我最近从php5.2.6迁移到了php5.6.22,现在我遇到了这个错误。

Unkwown error. 8192: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead

看起来在php5.6++中,preg_replace已被弃用。

http://php.net/manual/en/migration55.deprecated.php

这是我使用`preg_replace`函数的整个功能:

function mb_unserialize( $serial_str ) {
    $out = preg_replace( '!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
    return unserialize( $out );
}

有人能解释一下我应该如何使用这种类型的模式来实现preg_replace_callback函数吗?以及在这种情况下preg_replace_callback是如何工作的?

谢谢


preg_replace并没有被弃用,但是非PCRE的e(ereg)标志已经被弃用,以及ereg_replace也被弃用了——任何Perl兼容的正则表达式都可以。 - CD001
谢谢您的回答,基本上我只需要将 preg_replace 的模式从 '!s:(\d+):"(.*?)";!se' 改进为 '/!s:(\d+):"(.*?)";!se/',而不需要使用 preg_replace_callback 吗? - Adomas Kondrotas
在您的原始模式中,! 是 RegEx 匹配的起点和终点 - 最后的 se 字符是模式修饰符 (http://php.net/manual/en/reference.pcre.pattern.modifiers.php) - e 修饰符已经过时。您的模式可能应该是 /s:(\d+):"(.*?)";/s(尽管我会惊讶如果您需要 s 修饰符)。 - CD001
你提出的正则表达式 /s:(\d+):"(.*?)";/s 没有按预期工作,必须加上 ! 才能得到正确的输出。因此最终的正则表达式是 '/!s:(\d+):"(.*?)";!/s',再次感谢您的评论。 - Adomas Kondrotas
啊,我没意识到 ! 是模式的一部分;)以为它们是定界符(它们实际上就像定界符)。 - CD001
1个回答

0
一个正式的回答:
function mb_unserialize( string $serial_str ):string {
    return unserialize( preg_replace_callback(
        '/s:(?:\d+):"(.*?)";/s', // -- the first pair of parentheses is not used.
        function( array $matches ): string { // -- this is the callback.
            return 's:' . strlen( $matches[1] ) . ':"' . $matches[1] . '";';
        },
        $serial_str
    ));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接