Compare strlen and Mb_strlen
When the word Fu Quan is an English character, the two are the same. Here the main comparison, in Chinese and English mixed row, two results. (Encoding is UTF8 when testing)
Copy Code code as follows:
<?php
$str = ' Chinese a word 1 characters ';
echo strlen ($STR);
echo ' <br/> ';
Echo Mb_strlen ($str, ' UTF8 ');
Output results
14
6
?>
Result analysis: In strlen calculation, the Chinese character of a UTF8 is 3 lengths, so the length of "a character 1" is 3*4+2=14
When Mb_strlen is computed, the selected inner code is UTF8, and a Chinese character is computed as a length, so the length of the "1" character is 6
placeholder calculations for mixed-row strings in Chinese and English:
By using these two functions, you can jointly calculate how much of a Chinese-English mixed-row string is (a Chinese character occupies a position of 2 English characters are 1, calculated by: If a mixed-row string has a Chinese, b English, Occupy is:
Copy Code code as follows:
<?php
$str = ' Chinese a word 1 characters ';
Calculated as follows
Echo (strlen ($STR) + Mb_strlen ($str, ' UTF8 '))/2;
Echo
Output results
10
?>
For example, "Chinese a character 1" strlen ($STR) value is the 14,mb_strlen ($STR) value is 6, you can calculate the "Chinese a word 1" occupies the position is 10.
Attached to a website article:
It's still a question about Chinese. PHP's built-in string length function strlen does not handle the Chinese string correctly, it gets just the number of bytes in the string. For GB2312 Chinese encoding, strlen gets twice times the number of Chinese characters, and for UTF-8 encoded Chinese, it is 3 times times the difference (in UTF-8 code, a Chinese character occupies 3 bytes).
Using the Mb_strlen function can solve this problem better. The use of Mb_strlen is similar to strlen, except that it has a second optional parameter for specifying the character encoding. For example, to get the UTF-8 string $str length, you can use Mb_strlen ($str, ' UTF-8 '). If the second argument is omitted, PHP's internal encoding is used. The internal code can be obtained by the mb_internal_encoding () function. It's important to note that Mb_strlen is not a PHP core function, and you need to make sure that the "Extension=php_mbstring.dll" line exists and is not commented out, before you use it, to ensure that the Php_mbstring.dll is loaded in php.ini. Otherwise, there is an issue with undefined functions.