My preliminary understanding is that strlen can only calculate English characters, while mb_strlen can calculate the length of Chinese and English characters. Next I will introduce the differences between strlen and mb_strlen in detail. my preliminary understanding is that strlen can only calculate English characters, while mb_strlen can calculate the length of Chinese and English characters. Next I will introduce the differences between strlen and mb_strlen in detail.
Script ec (2); script
Definition and usage
The strlen () function returns the length of the string.
Syntax
Strlen (string) parameter description
String is required. Specifies the string to be checked.
The reference of the mb_strlen () function is the same.
Example
| The Code is as follows: |
|
|
$ Str = 'Chinese character a 1 ';
Echo strlen ($ str );
Echo'
';
Echo mb_strlen ($ str, 'utf8 ');
// Output result
// 14
// 6
?> |
Result Analysis:In strlen calculation, the Chinese character for UTF8 is 3 characters in length, so the length of "Chinese character a 1 character" is 3*4 + 2 = 14
When mb_strlen is calculated, if the selected inner code is UTF8, a Chinese character is regarded as 1 in length. Therefore, the length of "Chinese a character 1 character" is 6.
The built-in String Length function strlen in PHP cannot properly process Chinese strings. It only obtains the number of bytes occupied by strings. For GB2312 Chinese encoding, strlen obtains two times the number of Chinese characters, and for the UTF-8 encoding of Chinese, is three times the difference (in the UTF-8 encoding, A Chinese Character occupies 3 bytes ).
Using the mb_strlen function can better solve this problem. The usage of mb_strlen is similar to that of strlen, except that it has a second optional parameter for specifying character encoding. For example, you can use mb_strlen ($ str, 'utf-8') to get the $ str length of the UTF-8 '). If the second parameter is omitted, the internal code of PHP is used.
Notes
By default, php does not support the mb_strlen () function. You need to install the extension module. The installation method is as follows:
| The Code is as follows: |
|
|
Yum install php-mbstring |
Locate the location of mbstring. so. You can use the rpm name installed in rpm-ql.
Modify the/etc/php. ini configuration file and add
| The Code is as follows: |
|
|
Extension = php_mbstring.so |
Make sure that the php_mbstring.so module is in the path specified by the extension_dir = "/usr/lib64/php/modules" configuration.