substr()
substr() — Return part of a string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Returns the portion of string specified by the offset and length parameters.
Signature
substr(string $string, int $offset, ?int $length = null): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string | string | The input string. |
| $offset | int | 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. |
| $length | ?int | 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). |
Return value
Returns the extracted part of string, or an empty string.
Example
A runnable snippet:
echo substr('abcdef', 1), PHP_EOL; // bcdef echo substr("abcdef", 1, null), PHP_EOL; // bcdef; prior to PHP 8.0.0, empty string was returned echo substr('abcdef', 1, 3), PHP_EOL; // bcd echo substr('abcdef', 0, 4), PHP_EOL; // abcd echo substr('abcdef', 0, 8), PHP_EOL; // abcdef echo substr('abcdef', -1, 1), PHP_EOL; // f // Accessing single characters in a string // can also be achieved using "square brackets" $string = 'abcdef'; echo $string[0], PHP_EOL; // a echo $string[3], PHP_EOL; // d echo $string[strlen($string)-1], PHP_EOL; // f
Changelog
| Version | Change |
|---|---|
| 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. |
See also
strrchr(), substr_replace(), preg_match(), trim(), mb_substr(), wordwrap()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page substr() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.