String-Searching Functions

chinmay.sahoo

New member
Several functions find a string or character within a larger string. They come in three families: strpos( ) and strrpos( ), which return a position; strstr( ), strchr( ), and friends, which return the string they find; and strspn( ) and strcspn( ), which return how much of the start of the string matches a mask.

In all cases, if you specify a number as the “string” to search for, PHP treats that number as the ordinal value of the character to search for. Thus, these function calls are identical because 44 is the ASCII value of the comma:

Code:
$pos = strpos($large, ","); // find last comma
$pos = strpos($large, 44); // find last comma

All the string-searching functions return false if they can’t find the substring you specified. If the substring occurs at the start of the string, the functions return 0. Because false casts to the number 0, always compare the return value with === when testing for failure:

Code:
if ($pos === false) {
// wasn't found
} else {
// was found, $pos is offset into string
}
 
Back
Top