PHP substr() Function
The PHP substr() function returns the portion of string specified by the offset and length parameters.
Syntax
substr(string, offset, length)
Parameters
string |
Required. Specify the input string. |
offset |
Required. Specify offset parameter which indicates the starting position in the string.
|
length |
Optional. Specify the length of the returned string. Default is to the end of the string.
|
Return Value
Returns the portion of string or false on failure, or an empty string.
Example:
In the example below, where positive and negative offset parameters are used with this function.
<?php $str = "abcdefg"; echo "1. ".substr($str, 1)."\n"; echo "2. ".substr($str, 3)."\n"; echo "3. ".substr($str, 10)."\n"; echo "4. ".substr($str, -1)."\n"; echo "5. ".substr($str, -3)."\n"; echo "6. ".substr($str, -10)."\n"; ?>
The output of the above code will be:
1. bcdefg 2. defg 3. 4. g 5. efg 6. abcdefg
Example:
Consider one more example which shows results when length parameter is also added with this function.
<?php $str = "abcdefg"; echo "1. ".substr($str, 2, 3)."\n"; echo "2. ".substr($str, 2, -3)."\n"; echo "3. ".substr($str, 2, 8)."\n"; echo "4. ".substr($str, 2, -8)."\n"; echo "5. ".substr($str, 5, 3)."\n"; echo "6. ".substr($str, 5, -3)."\n"; echo "7. ".substr($str, 5, 8)."\n"; echo "8. ".substr($str, 5, -8)."\n"; ?>
The output of the above code will be:
1. cde 2. cd 3. cdefg 4. 5. fg 6. 7. fg 8.
❮ PHP String Reference