如何在php中将字符串转换为utf-8代码点

时间:2013-12-13 20:13:16

标签: php unicode utf-8 codepoint

我想转换一个字符串,如:

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

使用PHP

链接http://www.bareedsms.com/tools/UniCodeConverter.aspx

中的内容

2 个答案:

答案 0 :(得分:3)

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

  1. 快得多

  2. 更容易适应其他角色编码。

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

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

答案 1 :(得分:1)

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

我编辑函数以返回String。

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