Home  >  Article  >  Backend Development  >  javascript - php中chr()函数 为什么可以输出unicode字符?

javascript - php中chr()函数 为什么可以输出unicode字符?

WBOY
WBOYOriginal
2016-06-06 20:15:181278browse

php中chr()是对ascii码字符和对应的数字之间转换的
但是下面的代码为什么可以输出汉字呢?
比如汉字 '感' unt-8编码是 e6849f;

$a = chr(hexdec('e6')).chr(hexdec('84')).chr(hexdec('9f'));
echo $a;
可以输出汉字感,这是为什么?
chr对超出127的值会向后继续合并吗?

回复内容:

php中chr()是对ascii码字符和对应的数字之间转换的
但是下面的代码为什么可以输出汉字呢?
比如汉字 '感' unt-8编码是 e6849f;

$a = chr(hexdec('e6')).chr(hexdec('84')).chr(hexdec('9f'));
echo $a;
可以输出汉字感,这是为什么?
chr对超出127的值会向后继续合并吗?

ASCII码表示单字节字符(其中包括英文字母、数字、英文标点符号、不可见字符以及控制字符等等),它总是小于0x80,即小于十进制的128。当在处理字符时,如果字节小于0x80,则把它当作单字节来处理,否则会继续读取下一个字节,这通常跟编码有关,GBK会将2个字节当成一个字符来处理,UTF8则需要3个字节。有时候在PHP中需要做类似的处理,比如计算字符串中字符的个数(字符串可能包含单字节和多字节),strlen方法只能计算字节数,而mb_strlen需要开启扩展。类似这样的需求,其实很容易处理:

<code>function mbstrlen($str)
{
    $len = strlen($str);
     
    if ($len = 0x80)
        {
            $i += 2;
        }
    }
     
    return $count;
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn