It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

PHP substr()

Reading time 2 min
Published Aug 14, 2017
Updated Sep 27, 2019

PHP substr: Main Tips

  • PHP substr is one of the most common PHP string functions. It returns a part of a string.
  • The first argument specifies a string which will be trimmed.
  • The second argument specifies the position of the trim start. The third argument specifies the length of the string to be returned.
  • The start and length arguments can also be negative numbers.

Function Explained

PHP substr function returns the trimmed string. In other words, the method extracts a part of a string. In case of failure or an empty string, False is returned.

Example
<?php
  echo substr("Random text", 6);
?>

Syntax: Scheme and Parameters

As with all PHP string functions, using correct syntax is crucial here. Let's look at how the correct syntax for PHP substr function should look like:

substr(string, start, length)

Now, let's go through every element step by step to get a better understanding of what each parameter of the substr PHP function represents:

Parameter Description
string Necessary. Specifies the exact string to trim.
start Necessary. Sets a position for the start of trimming (counting from the start of the string if the number is positive, from the end - if it's negative).
0 sets start at the first character.
length Optional. Sets the length of the returned string (measured from the start parameter is a the number is positive, from the end - if it's negative).
The default value is 0.

Note: If the second argument has a negative value and the third argument is less than or equal to the second argument, the third argument (length) is automatically set to 0.

More Code Examples

The example below displays a few cases of using the start argument alone in the substr PHP function. The comments next to every case explain what will be returned:

Example
<?php 
  echo substr("Lama is the best pet", 8);
  echo substr("Lama is the best pet", 1);
  echo substr("Lama is the best pet", 5);
  echo substr("Lama is the best pet", -3);
  echo substr("Lama is the best pet", -8);
?>

Now, the example below displays cases when start and length arguments are used together. Again, the comments next to every case display what will be returned:

Example
<?php
  echo substr("Lama is the best pet", 0, 16);
  echo substr("Lama is the best pet", 2, 9);
  echo substr("Lama is the best pet", 0, 4);
  echo substr("Lama is the best pet", 0, -4);
  echo substr("Lama is the best pet", -9, -4);
?>