substr() function returns a part of a string. You provide a string and the position of the first character to be extracted (keep in mind that the first character has the index
0). From this character on, the rest of the string is returned. If you only want to return a part of it, provide the length in the third parameter. The preceding code shows
substr() in action and extracts
PHP: Hypertext Preprocessor.
substr function syntax
string substr ( string $string , int $start [, int $length ] )
This function returns the portion of string and accepts three parameters:
stringthe input string
startthe starting position
lengththe length to fetch
Extracting a Substring Using substr()
<?php $php = "PHP: Hypertext Preprocessor"; echo substr($php, 15, 4); //returns "Prep" ?>
If you want to count from the end of the string, use a negative value as the second parameter of
echo substr($php, -12, 4);
If you provide a negative value for the third parameter of
substr(), for example
n, the last
n characters are not part of the substring.
echo substr($php, -12, -8);
All of these calls to
Prep and are included into the complete code.