问题描述:
上午运行一个旧的php项目时报错:
PHP message: PHP Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead
Warning: preg_replace_callback(): Requires argument 2, 'iconv('UCS-2', 'UTF-8',
Function create_function() is deprecated
原因分析:
php 5.6之后的版本不再支持pre_replace()函数
自PHP 7.2起,函数create_function因为代码注入漏洞已被弃用。从PHP 5.3开始,执行此操作的首选方法是使用匿名函数。要捕获外部变量的值,请使用use声明。
解决方案:
将
preg_replace("#\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\1'))", json_encode($data));
替换成:
preg_replace_callback('/\\u([0-9a-f]{4})/i', function($matches){return iconv("UCS-2BE","UTF-8",pack("H*", $matches[1]));}, json_encode($data));
或直接封装为一个函数,可实现更好地复用:
function decodeUnicode($str){
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($matches){return iconv("UCS-2BE","UTF-8",pack("H*", $matches[1]));}, $str);
}
$str ='\u4e25\u9009\u7cbe\u9009\u4e86MUJI\u5236\u9020\u5546\u548c\u751f\u4ea7\u539f\u6599\uff0c\n\u7528\u51e0\u4e4e\u96f6\u5229\u6da6\u7684\u4ef7\u683c\uff0c\u5254\u9664\u54c1\u724c\u6ea2\u4ef7\uff0c\n\u8ba9\u7528\u6237\u4eab\u53d7\u539f\u54c1\u724c\u7684\u54c1\u8d28\u751f\u6d3b\u3002';
echo decodeUnicode($str);