Current Location: Home> Function Categories> mb_substr

mb_substr

Get part of the string
Name:mb_substr
Category:Multi-byte string
Programming Language:php
One-line Description:Get substrings of multibyte strings

Function name: mb_substr()

Applicable version: PHP 4 >= 4.0.6, PHP 5, PHP 7

Usage: The mb_substr() function is used to obtain a substring of a multibyte string. It is a function provided by the mbstring extension to handle multibyte character-encoded strings such as UTF-8.

Syntax: string mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] )

parameter:

  • $str: A multibyte string from which to get the substring.
  • $start: Specifies the start position of the substring. If $start is a positive number, the calculation starts from the left side of the string. If $start is negative, the calculation starts from the right side of the string.
  • $length: Optional parameter, specifying the length of the substring to be retrieved. The default value is NULL, which means to get all characters from the $start position to the end of the string.
  • $encoding: Optional parameter, specifying the name of the multibyte character encoding. The default value is mb_internal_encoding(), which is the current internal encoding.

Return value: Returns the obtained substring, and returns FALSE if an error occurs.

Example:

 $str = "Hello, 世界!"; echo mb_substr($str, 0, 5); // 输出:Hello echo mb_substr($str, 7, 3); // 输出:世界echo mb_substr($str, -2); // 输出:界!

In the example above, we first define a multibyte string $str that contains both English and Chinese characters. Then use the mb_substr() function to get substrings at different positions. In the first example, we get the first 5 characters from the starting position of the string, and the output is "Hello". In the second example, we get a substring of length 3, i.e. "World", starting from the 7th position of the string. In the third example, we use a negative number as the $start parameter, calculate from the right side of the string, and get the last 2 characters, namely "boundary!".

Note that since the mb_substr() function is a function provided by the mbstring extension, you need to make sure that the mbstring extension is installed and enabled before using it. You can determine whether the mbstring extension is enabled by checking whether the "extension=mbstring" line in the php.ini file is commented. If not enabled, you can remove the comments in the php.ini file and restart the server.

Similar Functions
Popular Articles