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.
$str = "Hello World";
$length = mb_strlen($str);
echo "字符串的长度为:" . $length;Output:
字符串的长度为:11Specifying 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.
$str = "你好,世界";
$length = mb_strlen($str, "UTF-8");
echo "字符串的长度为:" . $length;Output:
字符串的长度为:5Returning Byte Count
Set the third argument to "bytes" to have mb_strlen() return the number of bytes instead of characters.
$str = "Hello World";
$length = mb_strlen($str, "UTF-8", "bytes");
echo "字符串的长度为:" . $length;Output:
字符串的长度为:11Counting Character Occurrences
Use the third argument "count" to count how many times a specific character appears in the string.
$str = "Hello World";
$count = mb_strlen($str, "UTF-8", "count");
echo "字符'o'出现的次数为:" . $count;Output:
字符'o'出现的次数为:2Handling Different Encodings
mb_strlen()works with strings in various encodings; just provide the appropriate encoding name.
$str1 = "你好,世界";
$str2 = "こんにちは、世界";
$length1 = mb_strlen($str1, "UTF-8");
$length2 = mb_strlen($str2, "UTF-8");
echo "字符串1的长度为:" . $length1 . "<br>";
echo "字符串2的长度为:" . $length2;Output:
字符串1的长度为:5<br>字符串2的长度为:9Summary
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
