alternative for function preg_replace e/ modifier

时间秒杀一切 提交于 2019-12-11 06:26:48

问题


Anybody knows how to change this function with preg_replace and the e/ modifier The e/ modifier will be depreciated.

function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! preg_match("/[\200-\237]/", $string) and ! preg_match("/[\241-\377]/", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
     $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
    $string);

return $string;
}

回答1:


<?php
$string = preg_replace_callback("/([\340-\357])([\200-\277])([\200-\277])/",
    function($arr) {
        $val = (ord($arr[1]) - 224) * 4096
                + (ord($arr[2]) - 128) * 64
                + (ord($arr[3]) - 128);
        return "&#" . $val . ";";
    }, $string);


$string = preg_replace_callback("/([\300-\337])([\200-\277])/",
    function($arr)
    {
        $val = (ord($arr[1]) - 192) * 64 + ord($arr[2]) - 128;
        return "&#" . $val . ";";
    }, $string);


来源:https://stackoverflow.com/questions/12895555/alternative-for-function-preg-replace-e-modifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!