[Previous] [Contents] [Next]


Extracting a found portion of a string

The strstr( ) and stristr( ) functions search for the substring needle in the string haystack and return the portion of haystack from the first occurrence of needle to the end of haystack:

string strstr(string haystack, string needle)
string stristr(string haystack, string needle)

The strstr( ) search is case-sensitive; the stristr( ) search isn't. If the needle isn't found in the haystack string, both strstr( ) and stristr( ) return false. The following examples show how the functions work:

$var = "To be or not to be";

print strstr($var, "to");    //  "to be"
print stristr($var, "to");   //  "To be or not to be"
print stristr($var, "oz");   // false

The strrchr( ) function returns the portion of haystack by searching for the single character needle; however, strrchr( ) returns the portion from the last occurrence of needle:

string strrchr(string haystack, string needle)

Unlike strstr( ) and stristr( ), strrchr( ) searches for only a single character, and only the first character of the needle string is used. The following examples show how strrchr( ) works:

$var = "To be or not to be";

// Prints: "not to be"
print strrchr($var, "n");

// Prints "o be": Only searches for "o" which
// is found at position 14
print strrchr($var, "oz");

[Previous] [Contents] [Next]