Mastering PHP’s mb_strlen: Handle Multibyte Strings with Ease
This guide explains how to use PHP’s mb_strlen function to accurately measure the length of multibyte strings, covering installation of the mbstring extension, syntax, optional encoding, practical code examples, and common validation scenarios for robust backend development.
In development we often need to process multibyte strings such as Chinese or Japanese, and traditional PHP functions lack proper support. PHP provides the mb_strlen() function to obtain the length of multibyte strings. This article introduces its usage and offers code examples.
The mb_strlen() function is defined in the mbstring extension, so you must ensure the extension is installed and enabled. You can enable it by removing the comment in php.ini or by checking the current configuration with phpinfo().
mb_strlen() Function Syntax
int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )Parameters: $str: the multibyte string whose length is to be calculated. $encoding (optional): the character encoding to use. If omitted, the encoding returned by mb_internal_encoding() is used.
mb_strlen() Usage
Calculate the length of a Chinese string
<?php
$str = "你好,世界!";
echo mb_strlen($str); // Output: 7
?>This example shows that the string contains four Chinese characters and three ASCII characters, resulting in a length of 7.
Using a UTF-8 encoded string
You can specify the character encoding when handling strings with different encodings.
<?php
$str = "こんにちは世界";
echo mb_strlen($str, "UTF-8"); // Output: 6
?>Here the string consists of three Japanese characters and three Chinese characters, so the length returned is 6.
Validate string length against a limit
For example, you can restrict a string to a maximum number of characters:
<?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.";
}
?>If the string length exceeds the limit, the script outputs “String is too long.”; otherwise it outputs “String is within the limit.”
Through these examples you can see the basic usage of mb_strlen() and common scenarios such as length verification. When dealing with multibyte strings in real projects, mb_strlen() helps you handle them more accurately and improves 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.
