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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
