Skip to main content

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":

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the substr() function to extract 5 characters starting at index 6, then prints the result.
Output: PHP script

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:

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the substr() function starting at index 6 without specifying a length, to get the rest of the string, then prints the result.
Output: PHP script

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:

Prompt
Write a PHP script that stores "Hello World!" in a variable and uses the substr() function with a negative start index of -5 and a length of 3 to extract characters from the end, then prints the result.
Output: PHP script

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":

Prompt
Write a PHP script that stores "Hi, how are you?" in a variable and uses the substr() function with start index 5 and negative length -3, then prints the result.
Output: PHP script