【问题标题】:Hexadecimal code points from string in phpphp中字符串的十六进制代码点
【发布时间】:2012-04-03 09:41:42
【问题描述】:

我有一个希腊文本,我想将其转换为不带空格的十六进制代码点。只是一大串文本。

这正是我要找的东西 -> Unicode Hexadecimal code points for PHP 但它没有提供他是如何做到的实际代码。

【问题讨论】:

    标签: php


    【解决方案1】:

    基于original code和这个问题的答案:How to get code point number for a given character in a utf-8 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
        return ($unicode);   
    } // utf8_to_unicode
    

    所以:

    $greekString = "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ ";
    $hexArray = utf8_to_unicode($greekString);
    echo implode("", $hexArray);
    

    将输出:

    039103920393039403950396039703980399039A039B039C039D039E039F03A003A103A303A403A503A603A703A803A90032
    

    【讨论】:

    • Kenny 你的代码有问题。最有可能在 if ($thisValue
    • Γιώργο αν στείλεις αυτό ακριβώς this is a test The right convertion = 0393 03B9 03CE 03C1 03B3 03BF 0032 03B1 03BD 0032 03C3 03C4 03B5 03AF 03BB 03B5 03B9 03C2 0032 03B1 03C5 03C4 03CC 0032 03B1 03BA 03C1 03B9 03B2 03CE 03C2 0032 0116 0104 0105 0115 0032 0105 0115 0032 0097 0032 0116 0101 0115 0116 Your script = 0393 03B9 03CE 03C1 03B3 03BF 0020 03B1 03BD 0020 03C3 03C4 03B5 03AF 03BB 03B5 03B9 03C2 0020 03B1 03C5 03C4 03CC 0020 03B1 03BA 03C1 03B9 03B2 03CE 03C2 0020 0074 0068 0069 0073 0020 0069 0073 0020 0061 0020 0074 0065 0073 0074
    • 问题在于除希腊字符以外的任何其他字符,如 A-Z、空格等
    • 你说得对,我觉得应该是$unicode[] = str_pad(dechex($thisValue), 4, "0", STR_PAD_LEFT);
    【解决方案2】:

    这对我有用:

    header('Content-Type: text/html; charset=utf-8'); 
    
    bin2hex(iconv('UTF-8', 'UTF-16BE', 'your message')); 
    

    【讨论】:

      猜你喜欢
      • 2011-06-10
      • 2020-09-09
      • 2020-11-07
      • 2018-08-21
      • 2016-10-16
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      相关资源
      最近更新 更多