Home  >  Article  >  Backend Development  >  Get the natural length of strings containing Chinese and English

Get the natural length of strings containing Chinese and English

高洛峰
高洛峰Original
2017-02-09 09:14:151183browse

Test the awareness of encoding

Code example:

$str = '大家好abc';
echo strlen($str);
echo '<br/>';
echo mb_strlen($str,'utf-8');

The result is 12, 6

  • ##strlen() calculates the string Number of bytes, one English character is 1 byte, Chinese character is 2 bytes under GBK encoding, UTF8 is 3 bytes, so the number of bytes is 3*3+3 = 12

  • mb_strlen() requires mb_string extension, mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] ), the first parameter is the string to be detected, the second parameter is the encoding format, multi-byte Characters are recorded as 1


Test the awareness of encoding

Code example:

$str = '大家好abc';
echo strlen($str);
echo '<br/>';
echo mb_strlen($str,'utf-8');
The result is 12 , 6

  • strlen() calculates the number of bytes of the string. An English character is 1 byte, a Chinese character is 2 bytes in GBK encoding, and UTF8 is 3 characters. section, so the number of bytes is 3*3+3 = 12

  • mb_strlen() requires mb_string extension, mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] ) , the first parameter is the string to be detected, the second parameter is the encoding format, multi-byte characters are recorded as 1

More Get Included For articles related to the natural length of Chinese and English strings, please pay attention to the PHP Chinese website!

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