How to use the substr function in PHP?
The substr function is used to extract a portion of a string, and its syntax is as follows:
Return part of a string.
Explanation of parameters:
- $string: the string to be trimmed.
- $start: specifies the starting position for the extraction, which can be a negative number indicating counting from the end of the string.
- $length: Optional parameter, specifies the length of the substring to be extracted.
Return value:
- Return the extracted string, or false if unsuccessful.
Example of usage:
$string = "Hello, World!";
$result = substr($string, 0, 5);
echo $result; // 输出:Hello
$result = substr($string, 7);
echo $result; // 输出:World!
$result = substr($string, -6);
echo $result; // 输出:World!
$result = substr($string, 7, 5);
echo $result; // 输出:World
In the examples above, the substr function extracts a portion of the string based on the specified starting position and length, and displays the result on the screen.