Master Multibyte String Cutting in PHP with mb_substr – Examples & Tips

The article explains PHP's mb_substr() function, detailing its syntax, parameters, and how it correctly handles multibyte characters, with multiple code examples and notes on edge cases, making it essential for developers working on internationalized backend projects.

php Courses
php Courses
php Courses
Master Multibyte String Cutting in PHP with mb_substr – Examples & Tips

The mb_substr() function is a PHP string truncation function that can cut a portion of a multibyte string and return the new string. Unlike the regular substr() function, mb_substr() correctly handles multibyte characters (such as Chinese, Japanese, etc.), ensuring that the resulting string is not garbled or inaccurately cut. This is useful for internationalized projects.

mb_substr() function syntax:

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

Usage examples:

Example 1:

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

Since Chinese characters occupy 2 bytes, cutting the first 2 characters yields "今天".

Example 2:

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

Because Chinese characters occupy 2 bytes, cutting 4 characters starting from the second character gives "bcde".

Example 3:

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

If the length parameter is omitted, the function extracts until the end of the string.

Note that if $start exceeds the string length, mb_substr() returns an empty string. If $length is negative, it is ignored and the function extracts to the end.

When building multilingual websites, mb_substr() is convenient because it correctly handles multibyte characters without affecting page display.

Overall, mb_substr() is a practical PHP string function that reliably processes multibyte encoded characters such as Chinese and Japanese, making it essential for developers working on internationalized projects.

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.

BackendPHPString Manipulationmb_substrphp-functionsmultibyte
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.