PHP function ord() returns wrong code of cirilyc charecter

余生长醉 提交于 2019-12-25 04:24:09

问题


The utf-8 charcode of Russian 'A' is 1040 (decimal). Javascript do it right:

> 'А'.charCodeAt(0)
> 1040

But PHP code

<?php echo ord('А');?>

returns 208.

Please note that in the beginning of the PHP code I have:

mb_internal_encoding( 'UTF-8' );
setlocale( LC_CTYPE, 'ru_RU' );

How can I implement coding and decoding of UTF-8 characters in PHP? Use another function instead of ord?


回答1:


<?php
    mb_internal_encoding('UTF-8');
    header('Content-Type: text/html; charset=UTF-8');
?>
<html>
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
    <?php
        $the_char   = 'А';
        $byte_1     = $the_char[0];
        $byte_2     = $the_char[1];
        print (ord($byte_1) - 192) * 64 + (ord($byte_2) - 128);
    ?>
    </body>
</html>



回答2:


<?php

function ord_utf8($s){
return (int) ($s=unpack('C*',$s[0].$s[1].$s[2].$s[3]))&&$s[1]<(1<<7)?$s[1]:
($s[1]>239&&$s[2]>127&&$s[3]>127&&$s[4]>127?(7&$s[1])<<18|(63&$s[2])<<12|(63&$s[3])<<6|63&$s[4]:
($s[1]>223&&$s[2]>127&&$s[3]>127?(15&$s[1])<<12|(63&$s[2])<<6|63&$s[3]:
($s[1]>193&&$s[2]>127?(31&$s[1])<<6|63&$s[2]:0)));
}

print_r(ord_utf8('А'));

// Output 1040

You can found more explanations about it here https://stackoverflow.com/a/42600959/7558876



来源:https://stackoverflow.com/questions/22575085/php-function-ord-returns-wrong-code-of-cirilyc-charecter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!