PHP UNICODE 编码转换

2025-04-03 10:31:47
推荐回答(3个)
回答1:

Unicode是一个字符集,Unicode是定长的都为双字节.
这里我们常用的是utf8字符集编码,楼主是说的Unicode转换为UTF-8吧。

/**
* Unicode字符转换成utf8字符
* @param [type] $unicode_str Unicode字符
* @return [type] Utf-8字符
*/
function unicode_to_utf8($unicode_str) {
$utf8_str = '';
$code = intval(hexdec($unicode_str));
//这里注意转换出来的code一定得是整形,这样才会正确的按位操作
$ord_1 = decbin(0xe0 | ($code >> 12));
$ord_2 = decbin(0x80 | (($code >> 6) & 0x3f));
$ord_3 = decbin(0x80 | ($code & 0x3f));
$utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
return $utf8_str;
}

回答2:

  1. 编码时将字符串转成utf8,然后使用json_encode()出来就是unicode的

  2. 解码时,使用json_decode()

回答3:

在我博客中,有专门对此的几篇博客
思路就是把字符串分解成一个个中文英文字符,再把中文字符转换成UNICODE码

/**
* 将字符串转换成unicode编码
*
* @param string $input
* @param string $input_charset
* @return string
*/
function str_to_unicode($input, $input_charset = 'gbk'){
$input = iconv($input_charset, "gbk", $input);
preg_match_all("/[\x80-\xff]?./", $input, $ar);
$b = array_map('utf8_unicode_', $ar[0]);
$outstr = join("", $b);
return $outstr;
}

function utf8_unicode_($c, $input_charset = 'gbk'){
$c = iconv($input_charset, 'utf-8', $c);
return utf8_unicode($c);
}
// utf8 -> unicode
function utf8_unicode($c) {
switch(strlen($c)) {
case 1:
return $c;
case 2:
$n = (ord($c[0]) & 0x3f) << 6;
$n += ord($c[1]) & 0x3f;
break;
case 3:
$n = (ord($c[0]) & 0x1f) << 12;
$n += (ord($c[1]) & 0x3f) << 6;
$n += ord($c[2]) & 0x3f;
break;
case 4:
$n = (ord($c[0]) & 0x0f) << 18;
$n += (ord($c[1]) & 0x3f) << 12;
$n += (ord($c[2]) & 0x3f) << 6;
$n += ord($c[3]) & 0x3f;
break;
}
return "&#$n;";
}

/**
* 将unicode字符转换成普通编码字符
*
* @param string $str
* @param string $out_charset
* @return string
*/
function str_from_unicode($str, $out_charset = 'gbk'){
$str = preg_replace_callback("|&#([0-9]{1,5});|", 'unicode2utf8_', $str);
$str = iconv("UTF-8", $out_charset, $str);
return $str;
}

function unicode2utf8_($c){
return unicode2utf8($c[1]);
}
function unicode2utf8($c){
$str="";
if ($c < 0x80) {
$str.=$c;
} else if ($c < 0x800) {
$str.=chr(0xC0 | $c>>6);
$str.=chr(0x80 | $c & 0x3F);
} else if ($c < 0x10000) {
$str.=chr(0xE0 | $c>>12);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
} else if ($c < 0x200000) {
$str.=chr(0xF0 | $c>>18);
$str.=chr(0x80 | $c>>12 & 0x3F);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
}
return $str;
}

/**
* 模拟JS里的unescape
*
* @param unknown_type $str
* @return unknown
*/
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
#print_r($ar);
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
elseif(substr($v,0,3) == "")
$ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."
";
$ar[$k] = iconv("UCS-2","GB2312",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}
?>