Using mb_substr() for Multibyte-Safe Substring Extraction in PHP
The article explains PHP's mb_substr() function for multibyte-safe substring extraction, detailing its parameters, usage, and return value, and provides two practical code examples demonstrating how to extract Chinese characters with specified length and encoding.
The mb_substr() function in PHP performs a multibyte‑safe substring operation, allowing you to extract a portion of a string based on character count rather than byte count.
Signature: string mb_substr(string $str, int $start, int $length = NULL, string $encoding = mb_internal_encoding()) .
Parameters:
str : the input string.
start : the zero‑based position of the first character to include.
length : the maximum number of characters to extract; if omitted or NULL, extracts to the end of the string.
encoding : the character encoding to use; defaults to the internal encoding.
Return value: the extracted substring according to the specified start, length, and encoding.
Example 1 – extracting the first two characters of a Chinese string:
<?php
echo mb_substr("我是菜鸟", 0, 2);
// Output: 我是
?>Example 2 – specifying UTF‑8 encoding and extracting four characters:
<?php
header("content-type:text/html; charset=utf-8");
$string = "你好我好大家好";
echo mb_substr($string, 0, 4, 'utf-8');
// Output: 你好我好
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.