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.

php Courses
php Courses
php Courses
Master PHP’s mb_strlen: Accurately Measure Multibyte String Lengths

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() ] )
$str

is 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPcodingmb_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

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.