Get the natural length of strings containing Chinese and English

高洛峰
Release: 2023-03-05 15:26:01
Original
1199 people have browsed it

Test the awareness of encoding

Code example:

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

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');
Copy after login
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!