Backend Development 4 min read

Using PHP mb_substr() for Multibyte String Truncation

The article explains the PHP mb_substr() function, its syntax, parameter meanings, and provides multiple code examples demonstrating how to correctly truncate multibyte strings such as Chinese or Japanese without causing garbled output, along with important usage notes.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP mb_substr() for Multibyte String Truncation

The mb_substr() function is a PHP string‑truncation utility that works on multibyte strings, correctly handling characters like Chinese or Japanese, unlike the regular substr() which may produce garbled results.

mb_substr() Function Signature

<code>string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )</code>

Where $str is the input string, $start is the zero‑based start position, $length (optional) is the number of characters to extract, and $encoding (optional) specifies the character encoding, defaulting to the script’s encoding (usually UTF‑8).

Usage Examples

Example 1

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

Because each Chinese character occupies two bytes, extracting the first two characters yields "今天".

Example 2

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

Starting from the second character and taking four characters returns "bcde"; the multibyte characters are handled correctly.

Example 3

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

If the third parameter ( $length ) 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, and a negative $length is ignored, causing extraction up to the string’s end.

When building multilingual websites, mb_substr() is especially useful because it guarantees correct handling of multibyte characters, preserving page layout and readability.

Overall, mb_substr() is a practical PHP function for safely truncating multibyte strings, essential for developers working on internationalized or multilingual projects.

BackendPHPString()Tutorialmb_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

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.