Backend Development 4 min read

Using mb_strlen in PHP to Handle Multibyte Strings

This article explains how to enable the mbstring extension in PHP and use the mb_strlen function with UTF-8 encoding to accurately measure the length of multibyte strings, including practical code examples and techniques for checking empty strings.

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

In PHP, handling multibyte characters such as UTF-8 Chinese text can be problematic with traditional string functions, but the mb_strlen function provides an accurate way to obtain the length of multibyte strings.

Before using mb_strlen , ensure the mbstring extension is installed and enabled by locating the line ;extension=mbstring in the php.ini file, removing the leading semicolon, and restarting the web server or PHP interpreter.

;extension=mbstring

Below is a simple example demonstrating how to calculate the length of a multibyte string using mb_strlen :

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

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

The script defines $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.

Running the script outputs:

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

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

Beyond length calculation, mb_strlen can also be used to check whether a multibyte string is empty. By combining it with trim , you can remove surrounding whitespace and then test the length:

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

In this example, $str holds a string of only spaces; trim removes the spaces, and mb_strlen checks the length of the trimmed string to determine if it is empty.

These examples illustrate the powerful capabilities of mb_strlen for handling multibyte strings accurately and its usefulness when combined with other functions like trim in backend development.

backendphpmb_strlenMultibytestring length
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.