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

This article explains how PHP's mb_substr() function safely extracts portions of multibyte strings, details its syntax, parameters, and provides clear code examples demonstrating correct usage, edge cases, and its importance for multilingual web development.

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

mb_substr() is a PHP string function that can cut a part of a multibyte string and return the new string. Unlike substr(), mb_substr() correctly handles multibyte characters (e.g., Chinese, Japanese) ensuring no garbled output.

mb_substr() function syntax

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

Where $str is the input string, $start is the starting position (0‑based), $length is the length to cut, and $encoding is the 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, cutting the first two characters yields "今天".

Example 2

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

Since Chinese characters are two bytes, extracting four characters starting from position 1 gives "bcde".

Example 3

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

If the length parameter is omitted, the function returns the substring from the start position to 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 substring extends to the end.

When building multilingual websites, mb_substr() is convenient for correctly handling multibyte characters without affecting page display.

Overall, mb_substr() is a practical PHP function for safely cutting multibyte strings, 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.

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