PHP将汉字转换成Unicode编码的函数

这是一个将汉字转换成Unicode编码的PHP函数,支持GBK和UTF8编码。

function uni_decode ($uncode)
{
    $word = json_decode(preg_replace_callback('/&#(\d{5});/', create_function('$dec', 'return \'\\u\'.dechex($dec[1]);'), '"'.$uncode.'"'));
    return $word;
}

 对 Unicode 转换为汉字

function uni_decode ($uncode)
{
    $word = json_decode(preg_replace_callback('/&#(\d{5});/', create_function('$dec', 'return \'\\u\'.dechex($dec[1]);'), '"'.$uncode.'"'));
    return $word;
}

以下示例演示:



function uni_encode ($word)
{
	$word0 = iconv('gbk', 'utf-8', $word);
	$word1 = iconv('utf-8', 'gbk', $word0);
	$word =  ($word1 == $word) ? $word0 : $word;
    $word = json_encode($word);
    $word = preg_replace_callback('/\\\\u(\w{4})/', create_function('$hex', 'return \'&#\'.hexdec($hex[1]).\';\';'), substr($word, 1, strlen($word)-2));
    return $word;
}

$word = '将朱祖松和霍涛转为 Unicode 四字节编码! ';
echo uni_encode($word);

 

 上述将输出如下结果:

 

将朱祖松和霍涛转为 Unicode 四字节编码!

 

你可能感兴趣的:(PHP,php,convert)