PHP - Slicing Strings


Slicing

You can return a range of characters by using the substr() function.

Specify the start index and the number of characters you want to return.

Example

Start the slice at index 6 and end the slice 5 positions later:

$x = "Hello World!";
echo substr($x, 6, 5);
Try it Yourself »

Note The first character has index 0.


Slice to the End

By leaving out the length parameter, the range will go to the end:

Example

Start the slice at index 6 and go all the way to the end:

$x = "Hello World!";
echo substr($x, 6);
Try it Yourself »

Slice From the End

Use negative indexes to start the slice from the end of the string:

Example

Get the 3 characters, starting from the "o" in world (index -5):

$x = "Hello World!";
echo substr($x, -5, 3);
Try it Yourself »

Note The last character has index -1.


Negative Length

Use negative length to specify how many characters to omit, starting from the end of the string:

Example

Get the characters starting from the "W" in "World" (index 5) and continue until 3 characters from the end.

Should end up with "Wor":

$x = "Hello World!";
echo substr($x, 5, -3);
Try it Yourself »

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.