PHP Function Reference

PHP substr() Function



The PHP substr() function returns the portion of string specified by the offset and length parameters.

Syntax

substr(string, offset, length)

Parameters

string Required. Specify the input string.
offset Required. Specify offset parameter which indicates the starting position in the string.
  • If it is non-negative, the returned string will start at that offset in the string, counting from zero.
  • If it is negative, the returned string will start that far from the end of the string.
  • If string is less than offset characters long, false will be returned.
length Optional. Specify the length of the returned string. Default is to the end of the string.
  • If length is a positive number, then the returned string will have up to that many characters in it.
  • If length is a negative number then that many characters will be omitted from the end of string (after the start position has been calculated when a offset is negative). If offset denotes the position of this truncation or beyond, false will be returned.
  • If length is given and is 0, false or null, an empty string will be returned.

Return Value

Returns the portion of string or false on failure, or an empty string.

Example:

In the example below, where positive and negative offset parameters are used with this function.

<?php
$str = "abcdefg";

echo "1. ".substr($str, 1)."\n";
echo "2. ".substr($str, 3)."\n"; 
echo "3. ".substr($str, 10)."\n"; 
echo "4. ".substr($str, -1)."\n";
echo "5. ".substr($str, -3)."\n";  
echo "6. ".substr($str, -10)."\n";   
?>

The output of the above code will be:

1. bcdefg
2. defg
3. 
4. g
5. efg
6. abcdefg

Example:

Consider one more example which shows results when length parameter is also added with this function.

<?php
$str = "abcdefg";

echo "1. ".substr($str, 2, 3)."\n";
echo "2. ".substr($str, 2, -3)."\n";
echo "3. ".substr($str, 2, 8)."\n";
echo "4. ".substr($str, 2, -8)."\n";
echo "5. ".substr($str, 5, 3)."\n";
echo "6. ".substr($str, 5, -3)."\n";
echo "7. ".substr($str, 5, 8)."\n";
echo "8. ".substr($str, 5, -8)."\n";
?>

The output of the above code will be:

1. cde
2. cd
3. cdefg
4. 
5. fg
6. 
7. fg
8. 

❮ PHP String Reference