What is the function of mb_substr in PHP?

The mb_substr function in PHP is used to extract a substring from a specified string. Its purpose is to cut out a substring of a specified length from a string and return that substring.

The mb_substr function is similar to the substr function, but it can handle multi-byte characters (such as Chinese, Japanese, and other non-English characters). When dealing with non-English characters, using the substr function may result in garbled output, whereas the mb_substr function will correctly handle these characters and ensure that the substring is accurate.

The syntax of the mb_substr function is as follows:

This function extracts a part of a string starting at a specified position and with a specified length.

Description of Parameters:

  1. $str: the string to be cut or extracted
  2. $start: The starting position of the substring can be a negative number, indicating the position counted from the end of the string.
  3. $length: optional parameter indicating the length to be truncated. If not specified, the default is to truncate to the end of the string.
  4. $encoding: an optional parameter that indicates the encoding of the string, defaulting to the character encoding of the current script.

Example Usage:

$str = "Hello, 世界!";
$subStr = mb_substr($str, 0, 5);  // 从$str的第0个位置开始截取5个字符
echo $subStr;  // 输出:Hello

$subStr2 = mb_substr($str, 7);  // 从$str的第7个位置开始截取到字符串末尾
echo $subStr2;  // 输出:世界!

In summary, the mb_substr function ensures correct substring extraction, especially when handling non-English characters, to avoid any garbled text or incorrect results.

bannerAds