unicode轉漢字

function unicode_encode($name)
{
$name = iconv('UTF-8', 'UCS-2', $name);
$len = strlen($name);
$str = '';
for ($i = 0; $i < $len - 1; $i = $i + 2)
{
$c = $name[$i];
$c2 = $name[$i + 1];
if (ord($c) > 0)
{    // 兩個字節的文字
$str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
}
else
{
$str .= $c2;
}
}
return $str;
}

// 將UNICODE編碼後的內容進行解碼
function unicode_decode($name)
{
// 轉換編碼,將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;
}

上方是php的2個函數,一個將漢字轉成unicode,一個將unicode轉爲漢字。

工作中JSON.stringify(data);這個方法會將漢字轉成unicode,但是在php中將unicode解析爲漢字卻失敗了,於是研究發現,原來是unicode格式變了,正確的unicode格式是:\u5730\u65b9,漢字意思是‘地方’。但是在php反解析的時候這個unicode變成了u5730u65b9,沒了那個斜槓。於是對於這樣的情況改下格式就可以解析了,像這樣:$name=unicode_decode(str_replace('u','\\u','u5730u65b9'));這樣就能正確解析了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章