PHP UTF-8和Unicode编号互转

PHP UTF-8和Unicode编号互转

/**
* utf-8 转unicode
*
* @param string $name
* @return string
*/
function utf8_unicode($name){
$name = iconv('UTF-8', 'UCS-2', $name);
$len = strlen($name);
$str = '';
for ($i = ; $i < $len - ; $i = $i + ){
$c = $name[$i];
$c2 = $name[$i + ];
if (ord($c) > ){ //两个字节的文字
$str .= '\u'.base_convert(ord($c), , ).str_pad(base_convert(ord($c2), , ), , , STR_PAD_LEFT);
//$str .= base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
} else {
$str .= '\u'.str_pad(base_convert(ord($c2), , ), , , STR_PAD_LEFT);
//$str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
}
}
$str = strtoupper($str);//转换为大写
return $str;
} /**
* unicode 转 utf-8
*
* @param string $name
* @return string
*/
function unicode_decode($name)
{
$name = strtolower($name);
// 转换编码,将Unicode编码转换成可以浏览的utf-8编码
$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
preg_match_all($pattern, $name, $matches);
if (!empty($matches))
{
$name = '';
for ($j = ; $j < count($matches[]); $j++)
{
$str = $matches[][$j];
if (strpos($str, '\\u') === )
{
$code = base_convert(substr($str, , ), , );
$code2 = base_convert(substr($str, ), , );
$c = chr($code).chr($code2);
$c = iconv('UCS-2', 'UTF-8', $c);
$name .= $c;
}
else
{
$name .= $str;
}
}
}
return $name;
}
上一篇:DELPHI XE5开发WEB服务器及安卓手机客户端


下一篇:iOS和android游戏纹理优化和内存优化(cocos2d-x)