PHP Basic Tutorial
MySQL Connection
You can extract a portion of a string by using the substr()
function.
Specify the start index and the number of characters you want to return.
Syntax:
substr(string $string, int $start, int $length = ?);
$string
: The input string.
$start
: The starting position to slice. A positive number counts from the beginning (0-indexed). A negative number counts from the end of the string.
$length
(optional): The length of the substring to extract. If not provided, it extracts from $start
to the end of the string. A negative value of $length
will exclude characters from the end.
Try it yourself
Note
The first character has index 0.
By leaving out the length parameter, the range will go to the end:
Try it yourself
Use negative indexes to start the slice from the end of the string:
Try it yourself
Note
The last character has index -1.
When you pass a negative length value, it will exclude that many characters from the end of the string:
Try it yourself
In this case:
0
means start from the beginning of the string.-6
means exclude the last 6 characters, so "Hello, "
is returned.