【问题标题】:How can I convert a single Unicode value out of mb_convert_encoding into integer number如何将 mb_convert_encoding 中的单个 Unicode 值转换为整数
【发布时间】:2020-10-01 05:23:32
【问题描述】:

在 PHP 中,
如何将 mb_convert_encoding 中的 Unicode 值转换为整数

$A = mb_convert_encoding('و',"UTF-8");

$A = 'و';

我需要将'و' 转换为1608,这是'و' 的十进制等值

【问题讨论】:

    标签: php php-5.6


    【解决方案1】:

    你想要mb_ord()mb_ord() 给你一个 unicode 字符的代码点,mb_chr() 是相反的。

    <?php
    $A = 'و';
    echo mb_ord($A); // 1608
    echo mb_chr(1608); //و
    

    如果你不能使用php7,有一个php5 polyfill on the man page。我根据手册页上的内容稍作修改。

    if (!function_exists('mb_ord')) {
        function mb_ord($u) {
            $k = mb_convert_encoding($u,"UTF-8");
            $k1 = ord(substr($k, 0, 1));
            $k2 = ord(substr($k, 1, 1));
            return $k2 * 256 + $k1;
        }
    }
    

    【讨论】:

    • PHP 7以下就不行了,有没有别的办法?
    • 我测试了我的 php5.6 安装,它工作正常
    【解决方案2】:

    以下代码在所有 PHP 5、PHP 7 中都能正常工作

     $ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
     return hexdec(bin2hex($ret));
    

    【讨论】:

    • 这是 php5 比我发布的 +1 更清洁的解决方案
    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 2018-12-07
    • 2017-06-20
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2011-06-05
    相关资源
    最近更新 更多