This article describes how to obtain the length of a string in both Chinese and English. For more information about how to obtain the length of a string, see <g id = "1"> Check whether the length of a string is within the specified range </g>, naturally, I think of the strlen function in PHP.
The code is as follows:
$ Str = 'Hello world! ';
Echo strlen ($ str); // output 12
However, in PHP built-in functions, strlen and mb_strlen both calculate the length by calculating the number of bytes occupied by the string. the number of bytes occupied by Chinese characters varies with encoding. In GBK/GB2312, the Chinese character occupies 2 bytes, while in the UTF-8, the Chinese character occupies 3 bytes.
The code is as follows:
$ Str = 'Hello, World! ';
Echo strlen ($ str); // output 12 under GBK or GB2312, output 18 under UTF-8
While we often need to judge the length of the string is the number of characters, rather than the number of bytes occupied by the string, such as the PHP code under the UTF-8:
The code is as follows:
$ Name = 'Zhang Geng Chang ';
$ Len = strlen ($ name );
// Output FALSE because three Chinese characters in the UTF-8 account for 9 bytes
If ($ len> = 3 & $ len <= 8 ){
Echo 'true ';
} Else {
Echo 'false ';
}
So what convenient and practical methods can be used to obtain the length of a string containing Chinese characters? We can use regular expressions to calculate the number of Chinese characters, divided by 2 in GBK/GB2312 encoding, divided by 3 in UTF-8 encoding, and finally added the length of non-Chinese characters, however, this is not too troublesome.
WordPress uses the following code for reference:
The code is as follows:
$ Str = 'Hello, World! ';
Preg_match_all ('/./us', $ str, $ match );
Echo count ($ match [0]); // output 9
The idea is to use a regular expression to divide a string into a single character and calculate the number of matched characters using count, which is what we want.
But the above code in the UTF-8 encoding does not process GBK/GB2312 Chinese string, because GBK/GB2312 Chinese characters will be recognized as two characters and the number of Chinese characters calculated will double, so I came up with the following method:
The code is as follows:
$ Tmp = @ iconv ('gbk', 'utf-8', $ str );
If (! Empty ($ tmp )){
$ Str = $ tmp;
}
Preg_match_all ('/./us', $ str, $ match );
Echo count ($ match [0]);
Can be compatible with GBK/GB2312 and UTF-8 code, through a small amount of data testing, but not sure whether it is completely correct, hope there are Daniel pointing one or two.
The above is intended to ensure that the framework can be compatible with multiple encoding formats. However, in daily development, a project can determine the encoding type, therefore, you can use the following functions to conveniently obtain the string length:
The code is as follows:
Int iconv_strlen (string $ str [, string $ charset = ini_get ("iconv. internal_encoding")])