中文与unicode互转

20 篇文章 0 订阅
14 篇文章 4 订阅

/**
 * 中文 转化成 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);

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值