Specifications
Given the functions we have already looked at, we could use explode() or strtok() to
retrieve the individual words in the message, and then compare them using the == operator or
strcmp().
However, we could also do the same thing with a single function call to one of the string
matching or regular expression matching functions. These are used to search for a pattern
inside a string. We’ll look at each set of functions one by one.
Finding Strings in Strings: strstr(), strchr(), strrchr(),
stristr()
To find a string within another string you can use any of the functions strstr(), strchr(),
strrchr(), or stristr().
The function
strstr() is the most generic, and can be used to find a string or character match
within a longer string. Note that in PHP, the
strchr() function is exactly the same as
strstr(), although its name implies that it is used to find a character in a string, similar to the
C version of this function. In PHP, either of these functions can be used to find a string inside a
string, including finding a string containing only a single character.
The prototype for strstr() is as follows:
string strstr(string haystack, string needle);
You pass the function a haystack to be searched and a needle to be found. If an exact match
of the needle is found, the function returns the haystack from the needle onwards, otherwise
it returns false. If the needle occurs more than once, the returned string will start from the
first occurrence of needle.
For example, in the Smart Form application, we can decide where to send the email as follows:
$toaddress = “feedback@bobsdomain.com”; // the default value
// Change the $toaddress if the criteria are met
if (strstr($feedback, “shop”))
$toaddress = “retail@bobsdomain.com”;
else if (strstr($feedback, “delivery”))
$toaddress = “fulfilment@bobsdomain.com”;
else if (strstr($feedback, “bill”))
$toaddress = “accounts@bobsdomain.com”;
This code checks for certain keywords in the feedback and sends the mail to the appropriate
person. If, for example, the customer feedback reads “I still haven’t received delivery of
my last order,” the string “delivery” will be detected and the feedback will be sent to
fulfilment@bobsdomain.com.
Using PHP
P
ART I
106
06 7842 CH04 3/6/01 3:41 PM Page 106