What is the function of the php strlen function?
The strlen function is used to calculate the length of a string. It takes a string as a parameter and returns the number of characters in that string (excluding the null character).
The detailed explanation of the strlen() function is as follows:
Grammar: rules for how words are put together in a language.
strlen(string $string): int
Parameter:
- $string: the string to calculate the length of.
The return value of the strlen() function is the number of characters in the given string $string, which is the length of the string. If $string is an empty string, it returns 0.
Please pay attention to the following guidelines:
- The strlen() function calculates the number of characters in a string, not the number of bytes. Single-byte characters have the same number of characters and bytes, but for multi-byte characters (such as those in UTF-8 encoding), the number of characters may be different from the number of bytes.
- If $string contains non-ASCII characters, such as Chinese or Japanese, the mb_strlen() function should be used to get the correct character count.
1. “我不会说英文”
“I can’t speak English”
$str1 = 'Hello, World!';
echo strlen($str1); // 输出: 13
$str2 = '你好,世界!';
echo strlen($str2); // 输出: 19
$str3 = 'Hello, 世界!';
echo mb_strlen($str3); // 输出: 11
In the examples above, the first string contains English characters, with the same number of characters as bytes; the second string contains Chinese characters, and because each Chinese character occupies 3 bytes, the result obtained when using the strlen() function is the number of bytes, not the number of characters; the third string also contains Chinese characters, but using the mb_strlen() function can correctly determine the number of characters.