preg_replace_callback 实现比较优雅的替换

下面两种方法用于将类似한这样的片段转换成正常的文字

第一种方法先用正则将需要替换的片段找到,然后循环处理, 第二种方法使用了preg_replace_callback ,第二种方法代码量较少,看起来更加优雅.


方法一

<?php
$test_str="曾&#54620;李&#44397;&#50612;" ;
echo unescape($test_str);
function unescape($str) {
    preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
    $ar = $r[0];
    foreach($ar as $k=>$v) {
        if(substr($v,0,2) == "%u"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,-4)));
      }
        elseif(substr($v,0,3) == "&#x"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,3,-1)));
      }
        elseif(substr($v,0,2) == "&#") {
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("n",substr($v,2,-1)));
        }
    }
    return join("",$ar);
}
?>

方法二

<?php
$test_str="曾&#54620;李&#44397;&#50612;" ;
echo preg_replace_callback("/(%u.{4})|&#x.{4};|&#\d+;/ i", "unescape", $test_str);
function unescape($str_org) {    
    $str_org=$str_org[0];
        if(substr($str_org,0,2) == "%u"){
            $str_fin = iconv("UCS-2BE","UTF-8",pack("H4",substr($str_org,-4)));
      }
        elseif(substr($str_org,0,3) == "&#x"){
            $str_fin = iconv("UCS-2BE","UTF-8",pack("H4",substr($str_org,3,-1)));
      }
        elseif(substr($str_org,0,2) == "&#") {
            $str_fin = iconv("UCS-2BE","UTF-8",pack("n",substr($str_org,2,-1)));
        }
        return $str_fin ;
}
?>


你可能感兴趣的:(preg_replace_callback 实现比较优雅的替换)