The substr Function
The substr
function extracts and returns
a substring from a string. The original string
itself is not changed. The first parameter of the function
takes a string, the second - the character position
from where to start extraction, and the third
- the number of characters. Note that the numbering
of string characters starts from zero.
The second parameter can be negative
- in this case, the count will start from the end of the string,
and the last character will have the number
-1
.
The third parameter can be omitted - in this case, the extraction will occur to the end of the string.
The function works correctly only with Latin characters (single-byte characters).
Syntax
substr(string $string, int $offset, ?int $length = null): string
Example
Let's extract 3
characters from the string starting from
position 1
(from the second character, since
the first one has number 0):
<?php
echo substr('abcde', 1, 3);
?>
Code execution result:
'bcd'
Example
Let's extract all characters to the end of the string, starting from the second one (it has number 1):
<?php
echo substr('abcde', 1);
?>
Code execution result:
'bcde'
Example
Let's extract the third and second characters from
the end. To do this, specify the start of extraction as
-3
(this is the number of the third character from the end),
and the number of characters as 2
:
<?php
echo substr('abcde', -3, 2);
?>
Code execution result:
'cd'
Example
Let's extract the last 2
characters.
To do this, specify the position of the second to last character
(this is -2), and omit the third parameter - in
this case, the extraction will be to the end of the string:
<?php
echo substr('abcde', -2);
?>
Code execution result:
'de'
Example
Let's extract the last character:
<?php
echo substr('abcde', -1);
?>
Code execution result:
'e'
See Also
-
the
substr_replace
function,
which cuts out part of a string and replaces it with another