PHP uses the substr() and mb_substr() functions to intercept strings. The former is suitable for single-byte characters, and the latter supports multi-byte characters. Usage: substr(string, starting position, length); mb_substr(string, starting position, length, encoding). Example: intercept the first 5 characters: substr("Hello World", 0, 5); intercept starting from the 6th character: substr("Hello World", 5); intercept the middle part: substr("Hello World", 2 , 4); Processing multi-byte characters: mb_substr("Hello World",
PHP function to intercept strings
Goal: Intercept the specified part of the string
Function:
Usage:
substr( )
<code class="php">substr($string, $start, $length);</code>
mb_substr()
<code class="php">mb_substr($string, $start, $length, $encoding);</code>
Example:
Intercept the first 5 characters of the string:
<code class="php">$string = "Hello World"; $result = substr($string, 0, 5); // "Hello"</code>
Intercept the string from Starting from the 6th character:
<code class="php">$string = "Hello World"; $result = substr($string, 5); // "World"</code>
Intercept the middle part of the string:
<code class="php">$string = "Hello World"; $result = substr($string, 2, 4); // "llo "</code>
Use mb_substr to process multi-byte characters:
<code class="php">$string = "你好世界"; $result = mb_substr($string, 0, 3, "UTF-8"); // "你好"</code>
The above is the detailed content of Function to intercept string in php. For more information, please follow other related articles on the PHP Chinese website!