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.
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.
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.
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.
Examples
Example #3 Basic substr() usage
<?php
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
?>