unicode编码 php,PHP解码unicode编码

这篇文章主要介绍了PHP解码unicode编码 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下function unicode_decode($name) {

//方法一

$name = str_replace("\\\\u","\u",$name); $json = '{"str":"'.$name.'"}'; $arr = json_decode($json,true); if(empty($arr)) return '';

return $arr['str']; //方法二

// 转换编码,将Unicode编码转换成可以浏览的utf-8编码

$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';

preg_match_all($pattern, $name, $matches);

if (!empty($matches))

{

$name = '';

for ($j = 0; $j < count($matches[0]); $j++)

{

$str = $matches[0][$j];

if (strpos($str, '\\u') === 0)

{

$code = base_convert(substr($str, 2, 2), 16, 10);

$code2 = base_convert(substr($str, 4), 16, 10);

$c = chr($code).chr($code2);

$c = iconv('UCS-2', 'UTF-8', $c);

$name .= $c;

}

else

{

$name .= $str;

}

}

}

return $name;

}

以下是网上找的方法:

方案A(稳定版+推荐):function replace_unicode_escape_sequence($match) {

return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');

}$name = '\u65b0\u6d6a\u5fae\u535a';$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $name);echo $str; //输出: 新浪微博//咱将上述方案A给封装起来~~~(方案A稳定版+升级+推荐)class Helper_Tool{

static function unicodeDecode($data)

{

function replace_unicode_escape_sequence($match) {

return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');

}

$rs = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $data); return $rs;

}

}//调用$name = '\u65b0\u6d6a\u5fae\u535a';$data = Helper_Tool::unicodeDecode($name); //输出新浪微博

方案B(次推荐):<?phpfunction unicodeDecode($name){

$json = '{"str":"'.$name.'"}'; $arr = json_decode($json,true); if(empty($arr)) return '';

return $arr['str'];

}$name = '\u65b0\u6d6a\u5fae\u535a';echo unicodeDecode($name); //输出: 新浪微博

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值