/**
* 中文 转化成 unicode
* unicode 的三种表现形式:&#、&#x、\u
*
* @param string $str 中文字符串
* @param int $type 类型 1-十六进制(\u) 2-十六进制(&#x)0 3-十进制(&#)
*
* @return string
*/
function unicode_encode(string $str, int $type): string
{
$str = iconv('UTF-8', 'UCS-2', $str); // 字符串按要求的字符编码来转换
$arr = str_split($str, 2); // 将字符串转换为数组
$unicode = ''; // 类型
$prefix = ''; // 前缀
$suffix = ''; // 后缀
switch ($type) {
case 1:
$prefix .= '\u';
break;
case 2:
$prefix .= '&#x';
$suffix .= ';';
break;
case 3:
$prefix .= '&#';
$suffix .= ';';
break;
default:
die('非法参数');
}
// 组装unicode编码
foreach ($arr as $value) {
$tmp = bin2hex($value); // 二进制字符串转换为十六进制值
if ($type === 3) $tmp = hexdec($tmp); // 十六进制转换为十进制
$unicode .= $prefix . $tmp . $suffix;
}
return $unicode;
}
/**
* unicode 转化成 中文
* unicode 的三种表现形式:&#、&#x、\u
*
* @param string $unicode unicode编码
* @param int $type 1-十六进制(\u) 2-十六进制(&#x)0 3-十进制(&#)
*
* @return string
*/
function unicode_decode(string $unicode, int $type): string
{
if (!in_array($type, [1, 2, 3], true)) die('非法参数');
$unicode = strtr($unicode, ['\u' => '', '&#x' => '', '&#' => '', ';' => '']);
// 十进制
if ($type === 3) {
$arr = str_split($unicode, 5); // 将字符串转换为数组
$tmp = '';
foreach ($arr as $value) {
$tmp .= dechex($value); // 十进制转换为十六进制
}
$unicode = $tmp;
}
$bin = pack("H*", $unicode); // 将数据打包成二进制字符串
return mb_convert_encoding($bin, 'UTF-8', 'UCS-2BE'); // 字符串按要求的字符编码来转换
}
$a = unicode_encode('压密码贱', 1);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $a . "\r\n");
$b = unicode_encode('压密码贱', 2);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $b . "\r\n", FILE_APPEND);
// v($b);
$c = unicode_encode('压密码贱', 3);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $c . "\r\n", FILE_APPEND);
$d = unicode_decode('\u538b\u5bc6\u7801\u8d31', 1);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $d . "\r\n", FILE_APPEND);
$e = unicode_decode('压密码贱', 2);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $e . "\r\n", FILE_APPEND);
$f = unicode_decode('压密码贱', 3);
file_put_contents('D:\phpstudy_pro\WWW\test\0.txt', $f . "\r\n", FILE_APPEND);
运行结果: