Extracting Substrings


The 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 Prep from 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:

  1. string the input string

  2. start the starting position

  3. length the length to fetch

Extracting a Substring Using substr()

  $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 substr():

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 substr() return Prep and are included into the complete code.