码迷,mamicode.com
首页 > 其他好文 > 详细

preg_replace_callback 实现比较优雅的替换

时间:2015-11-11 20:54:24      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

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

第一种方法先用正则将需要替换的片段找到,然后循环处理, 第二种方法使用了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 实现比较优雅的替换

标签:

原文地址:http://my.oschina.net/qidis/blog/529081

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!