【问题标题】:How to Convert string to utf-8 codepoint in php如何在 php 中将字符串转换为 utf-8 代码点
【发布时间】:2013-12-13 20:13:15
【问题描述】:

我想转换如下字符串:

alnassre 
will be 0061006c006e00610073007300720065
عربي
will be 063906310628064a
a
will be 0061

使用 PHP

正如链接中的内容http://www.bareedsms.com/tools/UniCodeConverter.aspx

【问题讨论】:

标签: php unicode utf-8 codepoint


【解决方案1】:

我知道您已经找到了适合您的答案,但这应该是:

  1. 更快

  2. 更容易适应其他字符编码。

它确实依赖于iconv,但所有现代 PHP 安装都有它,对吧?

 function utf8_to_unicode_codepoints($text) {
     return ''.implode(unpack('H*', iconv("UTF-8", "UCS-4BE", $text)));
 }

【讨论】:

  • 请注意,这并不完全符合您的要求!但那是因为你问的有问题(具体来说,它不适用于所有 unicode 字符,因为代码点超过 0xFFFF)。要接近您的要求,请使用UTF-16BEUCS-2BE
【解决方案2】:

我找到了答案,但它返回数组here

我编辑函数以返回字符串。

function utf8_to_unicode($str) {

    $unicode = array();        
    $values = array();
    $lookingFor = 1;

    for ($i = 0; $i < strlen($str); $i++) {

        $thisValue = ord($str[$i]);

        if ($thisValue < 128) 
            $unicode[] = str_pad(dechex($thisValue), 4, "0", STR_PAD_LEFT);
        else {
            if (count($values) == 0) $lookingFor = ($thisValue < 224) ? 2 : 3;                
            $values[] = $thisValue;                
            if (count($values) == $lookingFor) {
                $number = ($lookingFor == 3) ?
                (($values[0] % 16) * 4096) + (($values[1] % 64) * 64) + ($values[2] % 64):
                (($values[0] % 32) * 64) + ($values[1] % 64);
                $number = strtoupper(dechex($number));
                $unicode[] = str_pad($number, 4, "0", STR_PAD_LEFT);
                $values = array();
                $lookingFor = 1;
            } // if
        } // if
    } // for
    $str="";
    foreach ($unicode as $key => $value) {
        $str .= $value;
    }


    return ($str);   
} // utf8_to_unicode

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2021-07-06
    • 2011-08-16
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多