php5.5 preg_replace 使用e问题,改写成preg_replace_callback

49次阅读

public function entity_decode($str, $charset=’UTF-8′)
{
if (stristr($str, ‘&’) === FALSE)
{
return $str;
}

    $str = html_entity_decode($str, ENT_COMPAT, $charset);
    $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
    return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
}

麻烦使用preg_replace_callback改写下该方法,谢谢。

已注销

phppublic function entity_decode($str, $charset='UTF-8'){
    if (stristr($str, '&') === false){
        return $str;
    }
    $str = html_entity_decode($str, ENT_COMPAT, $charset);
    $str = preg_replace_callback(
        '/&#x(0*[0-9a-f]{2,5})/i',
        function ($matches) {
            return chr(hexdec($matches[1]));
        },
        $str
    );
    return preg_replace_callback('/&#([0-9]{2,4})/',function ($matches) {
            return chr($matches[1]);
        },$str);
}

李引证

题主是从CI里复制的代码吧?上面那个答案中1改成0 我是这样写的。。

public function entity_decode($str, $charset='UTF-8')
{
    if (stristr($str, '&') === FALSE)
    {
        return $str;
    }

    $str = html_entity_decode($str, ENT_COMPAT, $charset);

    if(version_compare(PHP_VERSION, '5.5.0', '>='))
    {
        $str = preg_replace_callback(
            '/&#x(0*[0-9a-f]{2,5})/i',
            function ($matches) {
                return chr(hexdec($matches[0]));
            },
            $str
        );
        return preg_replace_callback(
            '/&#([0-9]{2,4})/',
            function ($matches) {
                return chr($matches[0]);
            },
            $str
        );  
    }

    $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
    return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
}

mxir

正文完