substr

PHP 4, PHP 5, PHP 7, PHP 8
substr - Return part of a string

substr( string$string, int$offset, [int|null$length = null] ): string

Returns the portion of string specified by the offset and length parameters.

Parameters

string

The input string.

offset

If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If offset is negative, the returned string will start at the offset'th character from the end of string.

If string is less than offset characters long, an empty string will be returned.

Using a negative offset
<?php
$rest 
substr("abcdef", -1);    // returns "f"
$rest substr("abcdef", -2);    // returns "ef"
$rest substr("abcdef", -31); // returns "d"
?>

length

If length is given and is positive, the string returned will contain at most length characters beginning from offset (depending on the length of string).

If length is given and is negative, 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, an empty string will be returned.

If length is given and is 0, an empty string will be returned.

If length is omitted or null, the substring starting from offset until the end of the string will be returned.

Using a negative length
<?php
$rest 
substr("abcdef"0, -1);  // returns "abcde"
$rest substr("abcdef"2, -1);  // returns "cde"
$rest substr("abcdef"4, -4);  // returns ""; prior to PHP 8.0.0, false was returned
$rest substr("abcdef", -3, -1); // returns "de"
?>

Return Values

Returns the extracted part of string, or an empty string.

Changelog

Version Description
8.0.0 length is nullable now. When length is explicitly set to null, the function returns a substring finishing at the end of the string, when it previously returned an empty string.
8.0.0 The function returns an empty string where it previously returned false.

Related Functions

Example of substr

Show all examples for substr

PHP Version:


Function substr:

Strings Functions

Most used PHP functions