Backend Development 5 min read

Using PHP mb_strlen to Handle Multibyte Strings

This article explains how to enable the mbstring extension in PHP and use the mb_strlen function to accurately measure multibyte string lengths, including examples with UTF-8 encoding, handling empty strings, and combining with trim for robust string validation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP mb_strlen to Handle Multibyte Strings

In PHP, handling multibyte characters is a common issue because languages such as Chinese use UTF-8 encoding, and traditional string length functions may give inaccurate results. PHP provides the convenient mb_strlen function to obtain the length of multibyte strings.

Before using mb_strlen , ensure that the mbstring extension is installed and enabled. In the php.ini file you should find the line:

;extension=mbstring

If the line starts with a semicolon, it is commented out; remove the semicolon and restart your web server or PHP interpreter.

The following simple example demonstrates how to use mb_strlen to calculate the length of a multibyte string.

<?php
$str = "你好,世界!";
$length = mb_strlen($str, "UTF-8");

echo "字符串 " . $str . " 的长度是: " . $length;
?>

This code defines a variable $str containing a multibyte string, calls mb_strlen with the UTF-8 encoding to compute its length, stores the result in $length , and prints the length using echo .

When the script is executed, the output will be:

字符串 "你好,世界!" 的长度是:6

The second argument "UTF-8" is specified because the string uses UTF-8 encoding; other encodings should be set accordingly.

Besides calculating length, mb_strlen can also be used to check whether a multibyte string is empty. If a string contains only whitespace or invisible characters, it is still considered non-empty.

To handle such cases, combine trim with mb_strlen to remove surrounding whitespace before checking the length.

<?php
$str = "    ";
$trimmedStr = trim($str);
if (mb_strlen($trimmedStr, "UTF-8") > 0) {
    echo "字符串不为空";
} else {
    echo "字符串为空";
}
?>

In this example, $str holds a multibyte string consisting only of spaces. After trimming, mb_strlen determines whether the resulting string has a length greater than zero and outputs the appropriate message.

These examples illustrate the powerful capabilities of mb_strlen for handling multibyte strings, providing accurate length calculations and enabling robust empty-string checks, which are essential when developing websites or processing multilingual data.

backendPHPMultibytestring lengthmbstring
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.