Specifications

There are two variants on strstr(). The first variant is stristr(), which is nearly identical
but is not case sensitive. This will be useful for this application as the customer might type
“delivery”, “Delivery”, or “DELIVERY”.
The second variant is strrchr(), which is again nearly identical, but will return the haystack
from the last occurrence of the needle onwards.
Finding the Position of a Substring: strpos(), strrpos()
The functions strpos() and strrpos() operate in a similar fashion to strstr(), except,
instead of returning a substring, they return the numerical position of a
needle within a
haystack.
The strpos() function has the following prototype:
int strpos(string haystack, string needle, int [offset] );
The integer returned represents the position of the first occurrence of the needle within the
haystack. The first character is in position 0 as usual.
For example, the following code will echo the value 4 to the browser:
$test = “Hello world”;
echo strpos($test, “o”);
In this case, we have only passed in a single character as the needle, but it can be a string of
any length.
The optional offset parameter is used to specify a point within the haystack to start searching.
For example
echo strpos($test, “o”, 5);
This code will echo the value 7 to the browser because PHP has started looking for the charac-
ter o at position 5, and therefore does not see the one at position 4.
The strrpos() function is almost identical, but will return the position of the last occurrence
of the needle in the haystack. Unlike strpos(), it only works with a single character needle.
Therefore, if you pass it a string as a needle, it will only use the first character of the string to
match.
In any of these cases, if the needle is not in the string, strpos() or strrpos() will return
false. This can be problematic because false in a weakly typed language such as PHP is
equivalent to 0, that is, the first character in a string.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
107
06 7842 CH04 3/6/01 3:41 PM Page 107