[Previous] [Contents] [Next]


Extracting a substring from a string

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

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

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]