php – 如何获取utf-8字符串中给定字符的代码点号?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 如何获取utf-8字符串中给定字符的代码点号?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想得到一个给定的UTF-8字符串的UCS-2代码点.例如,“hello”这个词应该是“0068 0065 006C 006C 006F”.请注意,字符可能来自任何语言,包括东亚语言等复杂脚本.

所以,问题归结为“将给定的字符转换为UCS-2代码点”

但是怎么样请,非常感谢,因为我很匆忙.

提前致谢

提问者答复的转录作为答案

感谢您的回复,但它需要在PHP v 4或5中完成但不是6.

字符串将是用户输入,从表单字段.

我想实现一个PHP版本的utf8to16或utf8decode like

function get_ucs2_codepoint($char)
{
    // calculation of ucs2 codepoint value and assign IT to $hex_codepoint
    return $hex_codepoint;
}

你可以用PHP来帮我吗,还是用PHP提供的版本呢?

再次感谢你.

Scott Reynen写了一个功能convert UTF-8 into Unicode.我发现它在 PHP documentation.
function utf8_to_unicode( $str ) {

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

    for ($i = 0; $i < strlen( $str ); $i++ ) {
        $thisValue = ord( $str[ $i ] );
    if ( $thisValue < ord('A') ) {
        // exclude 0-9
        if ($thisValue >= ord('0') && $thisValue <= ord('9')) {
             // number
             $unicode[] = chr($thisValue);
        }
        else {
             $unicode[] = '%'.dechex($thisValue);
        }
    } else {
          if ( $thisValue < 128) 
        $unicode[] = $str[ $i ];
          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 = dechex($number);
            $unicode[] = (strlen($number)==3)?"%u0".$number:"%u".$number;
                    $values = array();
                    $lookingFor = 1;
          } // if
        } // if
    }
    } // for
    return implode("",$unicode);

} // utf8_to_unicode

脚本宝典总结

以上是脚本宝典为你收集整理的php – 如何获取utf-8字符串中给定字符的代码点号?全部内容,希望文章能够帮你解决php – 如何获取utf-8字符串中给定字符的代码点号?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。