今天使PHP开发用到了Unicode的编码与解码,将unicode转为中文,再将中文转Unicode这样的操作是非常常见的,所以小编将这两个unicode中文互转函数给作为一个笔记保存起来,非常的简单,会用就行了。
1:下面来看PHP Unicode编码方法,将中文转为Unicode字符,例如将新浪微博转换为unicode字符串,代码如下:
function UnicodeEncode($str){ //split word preg_match_all('/./u',$str,$matches); $unicodeStr = ""; foreach($matches[0] as $m){ //拼接 $unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10); } return $unicodeStr; } $str = "浅笑"; echo UnicodeEncode($str);Unicode编码输出字符串:“u6d45u7b11”
2:unicode解码方法,将上面的unicode字符转换成中文,代码如下:
function unicodeDecode($unicode_str){ $json = '{"str":"'.$unicode_str.'"}'; $arr = json_decode($json,true); if(empty($arr)) return ''; return $arr['str']; } $unicode_str = "u6d45u7b11"; echo unicodeDecode($unicode_str);Unicode解码结果:“浅笑”
发表评论 取消回复