Master PHP’s mb_strlen: Accurately Measure Multibyte String Lengths
This guide explains how to enable the mbstring extension, use the mb_strlen() function with optional encoding, and apply practical examples—including Chinese and Japanese strings and length validation—to reliably handle multibyte strings in PHP development.
When working with multibyte characters such as Chinese or Japanese, the standard PHP string functions fall short, so the mb_strlen() function from the mbstring extension is used to obtain the correct length of multibyte strings.
Before using mb_strlen(), ensure the mbstring extension is installed and enabled. This can be done by removing the comment in php.ini or confirming activation with phpinfo().
The function signature is:
int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] ) $stris the target multibyte string, and $encoding is optional; if omitted, the encoding returned by mb_internal_encoding() is used.
Example 1 – Chinese string
<?php
$str = "你好,世界!";
echo mb_strlen($str); // Output: 7
?>The string contains four Chinese characters and three ASCII characters, resulting in a length of 7.
Example 2 – UTF‑8 Japanese string
<?php
$str = "こんにちは世界";
echo mb_strlen($str, "UTF-8"); // Output: 6
?>Specifying the UTF‑8 encoding, the function counts three Japanese characters and three Chinese characters, yielding a length of 6.
Example 3 – Length validation
<?php
$str = "This is a very long sentence.";
$max_length = 20;
if (mb_strlen($str) > $max_length) {
echo "String is too long.";
} else {
echo "String is within the limit.";
}
?>This snippet demonstrates how to enforce a maximum length constraint using mb_strlen().
In summary, mb_strlen() provides a reliable way to obtain the length of multibyte strings, optionally specify character encoding, and perform length checks, helping developers handle international text accurately and improve program stability.
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.
