Mastering PHP’s mb_substr: Handle Multibyte Strings with Ease

This article explains PHP's mb_substr() function, its signature, parameters, and provides clear examples showing how to correctly extract substrings from multibyte strings such as Chinese or Japanese without causing garbled output.

php Courses
php Courses
php Courses
Mastering PHP’s mb_substr: Handle Multibyte Strings with Ease
mb_substr()

is a PHP string function that extracts a portion of a multibyte string, correctly handling characters such as Chinese or Japanese, unlike substr(). This ensures the resulting substring is not garbled.

mb_substr() function signature

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

The parameters are: $str: the input string to be cut. $start: the starting position (0‑based). $length: the length to extract (optional). $encoding: character encoding, default is the script’s encoding (usually UTF‑8).

Usage examples

Example 1

$str = "今天是个好日子";
echo mb_substr($str, 0, 2); // outputs "今天"

Because Chinese characters occupy two bytes, extracting the first two characters yields “今天”.

Example 2

$str = "abcdefg你好";
echo mb_substr($str, 1, 4); // outputs "bcde"

Again, Chinese characters take two bytes, so extracting four characters starting from position 1 gives “bcde”.

Example 3

$str = "abcdefg你好";
echo mb_substr($str, 4); // outputs "g你好"

If the length argument is omitted, the function extracts to the end of the string.

Note that if $start exceeds the string length, mb_substr() returns an empty string. A negative $length is ignored and the substring runs to the end.

When building multilingual websites, mb_substr() is indispensable for correctly handling multibyte characters without breaking page layout.

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.

BackendString Manipulationmb_substrmultibyte
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.