[Previous] [Contents] [Next]

Finding and Extracting Substrings

PHP provides several simple and efficient functions that can identify and extract specific substrings of a string.

Extracting a substring from a string

The substr( ) function returns a substring from a source string:

string substr(string source, integer start [, integer length])

substr function

This function returns the portion of string specified by the start and length parameters.

substr accepts three parameters:

  1. source: The input string must have at least one character

  2. start: a positive or negative number

  3. length: a positive or negative number

When called with two arguments, substr( ) returns the characters from the source string starting from position start-counting from zero-to the end of the string. With the optional length argument, a maximum of length characters are returned. The following examples show how substr( ) works:

$var = "abcdefgh";
print substr($var, 2);       //  "cdefgh"
print substr($var, 2, 3);    //  "cde"
print substr($var, 4, 10);   //  "efgh"

If a negative start position is passed, the starting point of the returned string is counted from the end of the source string. If the length is negative, it's treated as the index, and the returned string ends length characters from the end of the source string. The following examples show how negative indexes can be used:

$var = "abcdefgh";
print substr($var, -1);      //  "h"
print substr($var, -3);      //  "fgh"
print substr($var, -5, 2);   //  "de"
print substr($var, -5, -2);  //  "def"

[Previous] [Contents] [Next]