Home > Article > Backend Development > PHP string function learning substr(), string substr_PHP tutorial
/*
Definition and Usage
The substr() function returns the extracted substring, or FALSE on failure.
Grammar
substr(string,start,length)
Parameter Description
string required. Specifies a part of the string to be returned.
start
Required. Specifies where in the string to begin.
Non-negative number - starting from the start position of the string, counting from 0.
Negative - Starts characters start from the end of string.
If the length of string is less than or equal to start, FALSE is returned.
length
Optional. Specifies the length of the string to be returned. The default is until the end of the string.
Positive number - up to length characters starting at start (depending on the length of string).
Negative number - remove length characters from the end of string
If length is provided with a value of 0, FALSE, or NULL, an empty string is returned.
*/
$str = "abcdefghijklmn";
$rest = substr($str, 0); // Return "abcdefghijklmn"
echo $rest . "
";
$rest = substr($str, 1, 3); // Return "bcd"
echo $rest . "
";
$rest = substr($str, -3); // Return "lmn"
echo $rest . "
";
$rest = substr($str, -3, 2); // Return "lm"
echo $rest . "
";
$rest = substr($str, 1, -3); // Return "bcdefghijk"
echo $rest . "
";
$rest = substr($str, -7, -3); // Return "hijk"
echo $rest . "
";
?>