Home >Backend Development >PHP Tutorial >PHP string function learning substr()_PHP tutorial
This article mainly introduces substr() for php string function learning. This article explains its definition, usage and parameters. Description, tips and comments as well as multiple usage examples, friends in need can refer to it
/*
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 - includes 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 . "
";
?>