String slicing allows you to return a specific range of characters using the substr()
function. You need to specify the start index and the number of characters you want to return.
Basic Slicing
Start the slice at index 6 and end the slice 5 positions later:
$vehicle = "Amazing Ducati!"; echo substr($vehicle, 7, 5);
In this case, the output will be Ducat
.
Note: The first character has index 0.
Slicing to the End
By omitting the length parameter, the slice will go to the end of the string:
$vehicle = "Amazing Ducati!"; echo substr($vehicle, 7);
The output will be Ducati!
.
Slicing from the End
Use negative indexes to start the slice from the end of the string:
$vehicle = "Amazing Ducati!"; echo substr($vehicle, -7, 5);
Here, the output will be Ducat
.
Note: The last character has index -1.
Negative Length
Specify how many characters to omit from the end of the string using negative length:
$sentence = "Hello, where are you?"; echo substr($sentence, 7, -3);
This code snippet will produce the output where are y
.