[Previous] [Contents] [Next]

Finding the position of a substring

The strpos( ) function returns the index of the first occurring substring needle in the string haystack:

integer strpos(string haystack, string needle [, integer offset])

When called with two arguments, the search for the substring needle is from the start of the string haystack at position zero. When called with three arguments, the search occurs from the index offset into the haystack. The following examples show how strpos( ) works:

$var = "To be or not to be";
print strpos($var, "T");     // 0
print strpos($var, "be");    // 3
// Start searching from the 5th character in $var
print strpos($var, "be", 4); // 16

The strrpos( ) function returns the index of the last occurrence of the single character needle in the string haystack:

integer strrpos(string haystack, string needle)

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

$var = "To be or not to be";
// Prints 13: the last occurrence of "t"
print strrpos($var, "t");
// Prints 0: Only searches for "T" which
// is found at position zero
print strrpos($var, "Tap");
// False: "Z" does not occur in the subject
onlyprint strrpos($var, "Zoo");

If the substring needle isn't found by strpos( ) or strrpos( ), both functions return false. The is-identical operator === should be used when testing the returned value from these functions against false. If the substring needle is found at the start of the string haystack, the index returned is zero and is interpreted as false if used as a Boolean value.

[Previous] [Contents] [Next]