substr()
The substr()
function returns a portion of a string specified by parameters for offset and length.
Syntax
substr($string, $offset, $length)
The substr()
function takes three parameters:
$string
: a requiredstring
from which a portion will be returned.$offset
: a requiredint
that specifies the start of the substring in the following manner:- Positive or zero values specify the zero-based character position from the start of the
string
. - Negative values indicate the character position from the end of the
string
. - A value greater than the length of
$string
will return an emptystring
.
- Positive or zero values specify the zero-based character position from the start of the
$length
: an optionalint
that specifies the number of characters to return in the following manner:- Positive values specify to return that number of characters, or characters up to the end of
$string
if fewer than$length
characters are left after$offset
is determined. - A
null
or omitted value will return characters from$offset
until the end of$string
. - Negative values will return characters from
$offset
until$length
characters from the end of$string
. - A value of zero, or a negative value that specifies a position before
$offset
, will return an emptystring
.
- Positive values specify to return that number of characters, or characters up to the end of
Example
The following example uses the substr()
function to return a substring from the given string
. Then the echo
command prints this new string
to the console:
<?phpecho (substr("I am learning PHP.", 14, 3));?>
The example will result in the following output:
PHP
Codebyte Example
The following example gives three examples of the substr()
function operating on the same string
.
All contributors
- cslylla58 total contributions
- StevenSwiniarski474 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.