substr() returns part of a string using a zero-based offset and an optional length. Negative offsets count from the end.
$text = 'plus2net.com';
echo substr($text, 0, 8); // plus2net
echo substr($text, -3); // com
$string="abcdefghijklmno";
$string=substr($string,4);
echo $string; // Output is efghijklmno
Syntax
substr (string $string, int $start [, int $length])
Use substr() to extract a byte-based portion of a string, starting at a specified position.
The optional length limits the returned portion. For multibyte character offsets, use mb_substr() when the mbstring extension is available.
| Parameter | DESCRIPTION |
|---|---|
$string | Required : Input string |
$start | Required : if not negative then return sting will start from $start position. if negative then return string will start from $start characters from end of the string. if the start offset exceeds the string length, PHP 8 returns an empty string ( ""); older PHP versions may differ.
The first char is 0 position from left. |
$length | Optional : if Positive then starting from $start, $length number of chars are returned.
if negative then $length number of chars will be omitted from end of the string. if $length is 0, the result is empty. Avoid passing false or null as a length; use an explicit integer or omit the argument.
if $length is omitted then the string starting from $start till the end is returned. |
$string="abcdefghijklmno";
$string=substr($string,0,4);
echo $string; // Output abcd
This will print abcd to the string. Here we have set the staring element as 0 so from the beginning 4 characters are collected.
$string="abcdefghijklmno";
$string=substr($string,2,4);
echo $string; // Output cdef
This will print cdef. Here as we have used 2 , so 4 characters starting from 2 character will be taken.
$string="abcdefghijklmno";
$string=substr($string,-6,4);
echo $string; // Output jklm
The above line of code will return jklm. You can see the negative number 6 mean the function will start collecting from the 6th position from the end. That is the from the character j . Now from j 4 characters, mean it is jklm.
$string="abcdefghijklmno";
$string=substr($string,-6,-1);
echo $string; // Output jklmn
The above line of codes will return jklmn. You can see the negative number 6 mean the function will start collecting from the 6th position from the end. That is the from the character j . Now from j all chars except last char, mean it is jklmn.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.