I officially started learning PHP today, but I accidentally discovered something that requires special attention when using PHP. For example: htmlmetacharsetutf-8body? Php $ name; print name:. strlen ($ name );? The output result of the bodyhtml code is: The name length is: 6.
I officially started learning PHP today, but I accidentally discovered something that requires special attention when using PHP. Example: htmlmeta charset = utf-8body? Php $ name = Naruto; print name Length:. strlen ($ name );? The output result of the/body/html code is: The name length is 6.
I officially started learning PHP today, but I accidentally discovered something that requires special attention when using PHP.
For example:
LengthIs: ". strlen ($ name);?>
The output result of this Code is: Name
Length6
First, let's discuss why this problem occurs: PHP built-inStringLengthThe strlen () function is incorrect.ProcessingChineseString, It only obtainsStringThe number of bytes occupied. For GB2312 Chinese encoding, The strlen value isChinese charactersThe number of 2 times, and for the UTF-8 encoding of Chinese, is 3 times the difference (in the UTF-8 encoding,Chinese characters3 bytes ).
If you want to use the strlen function to calculateStringOfLengthYes, too. The following example is taken online:
0xa0) { $tmpstr.=substr($str,$i,2); $i++; } else $tmpstr.=substr($str,$i,1); } return $tmpstr; }?>
However, apart from this, we can use the mb_strlen function to calculate:
Length". Mb_strlen ($ name," UTF-8 ");?>
The output result is: NameLength2
The usage of mb_strlen is similar to that of strlen, except that it has a second optional parameter for specifying character encoding.
It should be noted that mb_strlen is not a PHP core function. before using it, make sure that. the "php_mbstring.dll" line is loaded in ini to ensure that the "extension = php_mbstring.dll" line exists and is not commented out. Otherwise, the problem of undefined functions may occur.