This article mainly introduces the correct usage of substr and substring in PHP and related information about the relevant parameters. if you need it, you can refer to the strings intercepted in js, including substr and substring, in php, there is no substring function available directly, but there is a substr function.
Test it if you don't believe it. The following is a piece of correct code.
<? $ A = "me"; echo (substr ($ a,); // output me?> The following is an error code <? $ A = "me"; echo (subString ($ a,);?>
The substr () function returns part of the string.
Substr (string, start, length)
String: string to be truncated
Start:
Positive number-start at the specified position of the string
Negative number-starting from the specified position at the end of the string
0-start at the first character in the string
Length:
Optional. Specifies the length of the string to be returned. The default value is until the end of the string.
Positive number-return from the position of the start parameter
Negative number-return from the end of the string
Usage of PHP substr ()
Definition and usage
The substr () function returns part of the string. Garbled characters may occur when using the substr () function to intercept Chinese characters. we recommend that you use the mb_substr () function to intercept Chinese characters.
Syntax
Substr (string, start, length)
| Parameters |
Description |
| String |
Required. Specifies that a part of the string is to be returned. |
| Start |
Required. Specifies where the string starts.
- Positive number-start at the specified position of the string
- Negative number-starting from the specified position at the end of the string
- 0-start at the first character in the string
|
| Length |
Optional. Specifies the length of the string to be returned. The default value is until the end of the string.
- Positive number-return from the position of the start parameter
- Negative number-return from the end of the string
|
Tips and comments
Note: If start is a negative number and the length is less than or equal to start, the length is 0.
Example
<? Php $ str = 'Hello world! '; Echo substr ($ str, 4); // o world! Start from 4th on the left and start from the right to the end of the echo substr ($ str, 4, 5); // o wor start from 4th on the left and take 5 echo substr ($ str, 4, -1); // The echo substr ($ str,-8, 4) character between 4th from left and 1st from right in o world ); // o wo starts from 8th on the right and captures 4 echo substr ($ str,-8,-2) to the right ); // o worl starts from 8th to 2nd on the right?>