作者:手机用户2502875603 | 来源:互联网 | 2020-09-05 20:02
php汉字转unicode的方法:首先创建PHP示例代码文件;然后定义一个“unicode_encode”方法;接着再创建一个“unicode_decode”方法;最后通过定义好的方法进行转换即可。
php汉字转unicode的方法:首先创建PHP示例代码文件;然后定义一个“unicode_encode”方法;接着再创建一个“unicode_decode”方法;最后通过定义好的方法进行转换即可。
php汉字转Unicode编码函数
/**
* $str 原始字符串
* $encoding 原始字符串的编码,默认GBK
* $prefix 编码后的前缀,默认"&#"
* $postfix 编码后的后缀,默认";"
*/
function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
$str = iconv($encoding, 'UCS-2', $str);
$arrstr = str_split($str, 2);
$unistr = '';
for($i = 0, $len = count($arrstr); $i <$len; $i++) {
$dec = hexdec(bin2hex($arrstr[$i]));
$unistr .= $prefix . $dec . $postfix;
}
return $unistr;
}
/**
* $str Unicode编码后的字符串
* $encoding 原始字符串的编码,默认GBK
* $prefix 编码字符串的前缀,默认"&#"
* $postfix 编码字符串的后缀,默认";"
*/
function unicode_decode($unistr, $encoding = &#39;GBK&#39;, $prefix = &#39;&#&#39;, $postfix = &#39;;&#39;) {
$arruni = explode($prefix, $unistr);
$unistr = &#39;&#39;;
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(&#39;UCS-2&#39;, $encoding, $unistr);
}
使用:
//GBK字符串测试
$str = &#39;哈哈&#39;;
echo $str.&#39;
&#39;;
$unistr = unicode_encode($str);
echo $unistr.&#39;
&#39;; // <&#98;>&#21704;&#21704;<&#47;&#98;>
$str2 = unicode_decode($unistr);
echo $str2.&#39;
&#39;; //哈哈
//UTF-8字符串测试
$utf8_str = iconv(&#39;GBK&#39;, &#39;UTF-8&#39;, $str);
echo $utf8_str.&#39;
&#39;; // 鍝堝搱 注:UTF在GBK下显示的乱码!可切换浏览器的编码测试
$utf8_unistr = unicode_encode($utf8_str, &#39;UTF-8&#39;);
echo $utf8_unistr.&#39;
&#39;; // <&#98;>&#21704;&#21704;<&#47;&#98;>
$utf8_str2 = unicode_decode($utf8_unistr, &#39;UTF-8&#39;);
echo $utf8_str2.&#39;
&#39;; // 鍝堝搱
//其它后缀、前缀测试
$prefix_unistr = unicode_encode($str, &#39;GBK&#39;, "\\u", &#39;&#39;);
echo $prefix_unistr.&#39;
&#39;; // \u60\u98\u62\u21704\u21704\u60\u47\u98\u62
$profix_unistr2 = unicode_decode($prefix_unistr, &#39;GBK&#39;, "\\u", &#39;&#39;);
echo $profix_unistr2.&#39;
&#39;; //哈哈
推荐:《PHP教程》
以上就是php汉字如何转unicode的详细内容,更多请关注 第一PHP社区 其它相关文章!