Using PHP mb_strlen() to Accurately Measure Multibyte String Lengths
This article explains how to use PHP's mb_strlen() function to accurately measure string lengths, handle multibyte characters, specify encodings, retrieve byte counts, count character occurrences, and work with different language encodings, providing clear code examples for each case.
Basic Usage
The mb_strlen() function calculates the length of a string, correctly handling multibyte characters. Provide the string as the first argument.
<code>$str = "Hello World";
$length = mb_strlen($str);
echo "字符串的长度为:" . $length;
</code>Output: 字符串的长度为:11
Specifying Character Encoding
When the string contains multibyte characters, specify the correct encoding (e.g., UTF-8) as the second argument to obtain an accurate length.
<code>$str = "你好,世界";
$length = mb_strlen($str, "UTF-8");
echo "字符串的长度为:" . $length;
</code>Output: 字符串的长度为:5
Returning Byte Count
Set the third argument to "bytes" to have mb_strlen() return the number of bytes instead of characters.
<code>$str = "Hello World";
$length = mb_strlen($str, "UTF-8", "bytes");
echo "字符串的长度为:" . $length;
</code>Output: 字符串的长度为:11
Counting Character Occurrences
Use the third argument "count" to count how many times a specific character appears in the string.
<code>$str = "Hello World";
$count = mb_strlen($str, "UTF-8", "count");
echo "字符'o'出现的次数为:" . $count;
</code>Output: 字符'o'出现的次数为:2
Handling Different Encodings
mb_strlen() works with strings in various encodings; just provide the appropriate encoding name.
<code>$str1 = "你好,世界";
$str2 = "こんにちは、世界";
$length1 = mb_strlen($str1, "UTF-8");
$length2 = mb_strlen($str2, "UTF-8");
echo "字符串1的长度为:" . $length1 . "<br>";
echo "字符串2的长度为:" . $length2;
</code>Output: 字符串1的长度为:5<br>字符串2的长度为:9
Summary
The mb_strlen() function is a PHP string length utility that correctly handles multibyte characters. By specifying the character encoding, requesting byte counts, or counting character occurrences, developers can obtain precise length information in multilingual environments.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.