繁体   English   中英

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

[英]How to Convert string to utf-8 codepoint in php

我想将字符串转换为:

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

使用PHP

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

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

  1. 快多了

  2. 适应其他字符编码要容易得多。

它确实取决于iconv ,但是所有现代PHP安装都具有该功能,对吗?

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

我找到了答案,但它在这里返回数组

我编辑该函数以返回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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM