PHP mb_substr() Function: Definition, Parameters, Return Value, Usage Notes, and Examples
The PHP mb_substr() function provides multibyte‑aware substring extraction, allowing developers to specify start position, length, and encoding to correctly handle Unicode strings, with detailed parameter explanations, return values, important usage notes, and practical code examples.
The PHP mb_substr() function is a multibyte‑aware substring function that correctly handles multibyte characters, avoiding issues that arise with standard string functions.
Function Definition
<code>mb_substr(string $str, int $start, int $length = null, string $encoding = null): string</code>Parameter Explanation
$str : The input string to be sliced.
$start : The starting position. Positive values count from the beginning; negative values count from the end.
$length : The number of characters to extract. Positive values extract forward from the start; negative values extract backward from the end. If omitted, extraction continues to the end of the string.
$encoding : The character encoding. If provided, the function uses this encoding; otherwise it attempts to detect the encoding automatically.
Return Value
The function returns the extracted substring.
Important Notes
The function operates on multibyte character sequences, so ensure the input string is encoded accordingly before using mb_substr() .
Although the fourth parameter $encoding can be omitted, explicitly specifying the encoding (e.g., "UTF-8") is recommended for reliable results.
When using negative numbers, mb_substr() treats them differently from standard substring functions: a negative start position counts from the beginning of the string rather than from the end.
Example Usage
Extract a portion of a string
<code>$str = "Hello, 世界!";
$substring = mb_substr($str, 0, 5, "UTF-8"); // returns "Hello"
</code>Extract from the end of a string
<code>$str = "Hello, 世界!";
$substring = mb_substr($str, -7, 5, "UTF-8"); // returns "世界"
</code>Automatic encoding detection
<code>$str = "Hello, 世界!";
$substring = mb_substr($str, 0, 5); // returns "Hello"
</code>Specify encoding explicitly
<code>$str = "你好,世界!";
$substring = mb_substr($str, 0, 5, "UTF-8"); // returns "你好"
</code>When using mb_substr() , ensure the string is a multibyte sequence and specify the correct encoding to obtain accurate results.
Recommended PHP Learning Resources
Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Expert Course
Workerman+TP6 Real‑time Chat System – Limited Time Offer
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.