$string="abcdefghijklmno";
$string=substr($string,4);
echo $string; // Output is efghijklmno
Syntax
substr (string $string, int $start [, int $length])
We can take out a part of a string by using substr function in PHP. This way starting from any location to any location we can copy the string.
We can see the optional element of length which will collect that many length of string.
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 start char is more than the length of the input string then FALSE is returned. 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 or False or null then an empty string is returned. 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.