PHP substr() - Slice a String
When you only need part of a string, slice it with substr().
You tell the function where to begin (the start index) and how many characters you want back.
Note: Counting starts at 0, so index 0 is the first character.
Example
Begin at index 6 and take 5 characters, which gives the word "World":
Output: PHP script
<?php
$x = "Hello World!";
echo substr($x, 6, 5);
?>
Slice String to the End
The length parameter is optional. Without it, the slice runs through to the last character.
Example
Begin at index 6 and keep everything after it, including the exclamation mark:
Output: PHP script
<?php
$x = "Hello World!";
echo substr($x, 6);
?>
Slice String From the End
A negative start index counts backwards from the end of the string.
Note: Index -1 is the very last character.
Example
Index -5 points to the "o" in "World", and from there we take 3 characters:
Output: PHP script
<?php
$x = "Hello World!";
echo substr($x, -5, 3);
?>
Negative Length
The length can be negative too. In that case, it says how many characters to leave off at the end of the string.
Example
In "Hi, how are you?", begin at index 5 and stop just before the third character from the end (index -3). The slice is "ow are y":
Output: PHP script
<?php
$x = "Hi, how are you?";
echo substr($x, 5, -3);
?>