今天使PHP開發(fā)用到了Unicode的編碼與解碼,將unicode轉(zhuǎn)為中文,再將中文轉(zhuǎn)Unicode這樣的操作是非常常見的,所以小編將這兩個unicode中文互轉(zhuǎn)函數(shù)給作為一個筆記保存起來,非常的簡單,會用就行了。

1:下面來看PHP Unicode編碼方法,將中文轉(zhuǎn)為Unicode字符,例如將新浪微博轉(zhuǎn)換為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字符轉(zhuǎn)換成中文,代碼如下:

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解碼結(jié)果:“淺笑”