Specifications

return a number greater than zero. If str1 is less than str2, strcmp() will return a number
less than zero. This function is case sensitive.
The function strcasecmp() is identical except that it is not case sensitive.
The function strnatcmp() and its non-case sensitive twin, strnatcasecmp(), were added in
PHP 4. These functions compare strings according to a natural ordering, which is more the
way a human would do it. For example, strcmp() would order the string “2” as greater than
the string “12” because it is lexicographically greater. strnatcmp() would do it the other
way around. You can read more about natural ordering at http://www.linuxcare.com.au/
projects/natsort/
Testing String Length with strlen()
We can check the length of a string with the strlen() function. If you pass it a string, this
function return its length. For example,
strlen(“hello”) returns 5.
This can be used for validating input data. Consider the email address on our form, stored in
$email. One basic way of validating an email address stored in $email is to check its length.
By my reasoning, the minimum length of an email address is six charactersfor example,
a@a.to if you have a country code with no second level domains, a one-letter server name, and
a one-letter email address. Therefore, an error could be produced if the address was not this
length:
if (strlen($email) < 6)
{
echo “That email address is not valid”;
exit; // finish execution of PHP script
}
Clearly, this is a very simplistic way of validating this information. We will look at better ways
in the next section.
Matching and Replacing Substrings with String
Functions
Its common to want to check if a particular substring is present in a larger string. This partial
matching is usually more useful than testing for equality.
In our Smart Form example, we want to look for certain key phrases in the customer feedback
and send the mail to the appropriate department. If we want to send emails talking about Bobs
shops to the retail manager, we want to know if the word shop(or derivatives thereof) appear
in the message.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
105
06 7842 CH04 3/6/01 3:41 PM Page 105