今天就跟大家聊聊有關利用PHP怎么對Unicode編碼進行轉換,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
具體如下:
<?php
/**
* $str 原始中文字符串
* $encoding 原始字符串的編碼,默認utf-8
* $prefix 編碼后的前綴,默認"&#"
* $postfix 編碼后的后綴,默認";"
*/
function unicode_encode($str, $encoding = 'utf-8', $prefix = '&#', $postfix = ';') {
//將字符串拆分
$str = iconv("UTF-8", "gb2312", $str);
$cind = 0;
$arr_cont = array();
for ($i = 0; $i < strlen($str); $i++) {
if (strlen(substr($str, $cind, 1)) > 0) {
if (ord(substr($str, $cind, 1)) < 0xA1) { //如果為英文則取1個字節
array_push($arr_cont, substr($str, $cind, 1));
$cind++;
} else {
array_push($arr_cont, substr($str, $cind, 2));
$cind+=2;
}
}
}
foreach ($arr_cont as &$row) {
$row = iconv("gb2312", "UTF-8", $row);
}
//轉換Unicode碼
foreach ($arr_cont as $key => $value) {
$unicodestr.= $prefix . base_convert(bin2hex(iconv('utf-8', 'UCS-4', $value)), 16, 10) .$postfix;
}
return $unicodestr;
}
/**
* $str Unicode編碼后的字符串
* $decoding 原始字符串的編碼,默認utf-8
* $prefix 編碼字符串的前綴,默認"&#"
* $postfix 編碼字符串的后綴,默認";"
*/
function unicode_decode($unistr, $encoding = 'utf-8', $prefix = '&#', $postfix = ';') {
$arruni = explode($prefix, $unistr);
$unistr = '';
for ($i = 1, $len = count($arruni); $i < $len; $i++) {
if (strlen($postfix) > 0) {
$arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
}
$temp = intval($arruni[$i]);
$unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
}
return iconv('UCS-2', $encoding, $unistr);
}
$str = "PHP編程:www.jb51.net";
$unistr = unicode_encode($str);
$unistr2 = unicode_decode($unistr);
echo $unistr . '<br />';
echo $unistr2 . '<br />';
$unistr = unicode_encode($str,'GBK','\\u');
$unistr2 = unicode_decode($unistr,'GBK','\\u');
echo $unistr . '<br />';
echo $unistr2 . '<br />';PS:下面測試過這個函數比較好用,該代碼需要在utf-8編碼環境下運行
function unicode_encode($name) {//Unicode編碼
$jsonarr = array($name);
$jsonstr = json_encode($jsonarr);
if (empty ($jsonstr))
return '';
return substr($jsonstr,2,-2);
}
function unicode_decode($name) {//Unicode解碼
$json = '{"str":"' . $name . '"}';
$arr = json_decode($json, true);
if (empty ($arr))
return '';
return $arr['str'];
}
$test = "\u811a\u672c\u4e4b\u5bb6";
echo "unicode解碼:".unicode_decode($test)."<br/>";
echo "unicode編碼:".unicode_encode('億速云')."<br/>";看完上述內容,你們對利用PHP怎么對Unicode編碼進行轉換有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。