【问题标题】:Need help to replace preg_replace_callback in php?需要帮助替换 php 中的 preg_replace_callback?
【发布时间】:2017-08-31 00:45:00
【问题描述】:

需要帮助解决如下错误,

preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in line 601

以下代码出错,

$string = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
$string = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $string);

AM 试过了。

$string =  preg_replace_callback('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))',function ($match) {
return ($match[1]);
}, $string);

但还是出现这样的错误?

Requires argument 2, 'chr(hexdec("\1"))'

【问题讨论】:

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


【解决方案1】:

如错误所示,您的 PHP 版本不再支持 e 修饰符。

preg_replace_callback 等效项如下所示:

$string = preg_replace_callback('~&#x([0-9a-f]+);~i', function ($m) {
    return chr(hexdec($m[1]));
}, $string);

注意:不需要正则表达式中的 0*,因为后面的模式会捕获零,并且不需要在捕获组中捕获这些零。

但是,由于您使用的是等于或高于 5.5 的 PHP 版本(如 those versions produce the error),您可以依赖 html_entity_decode

$string = html_entity_decode($string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2014-03-08
    • 2014-10-31
    • 1970-01-01
    • 2014-03-09
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多