Prev | Current Page 317 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Another common point of confusion regarding this function surrounds its behavior of
returning 0 if the two strings are equal. This is different from executing a string comparison
using the == operator, like so:
if ($str1 == $str2)
While both accomplish the same goal, which is to compare two strings, keep in
mind that the values they return in doing so are different.
Comparing Two Strings Case Insensitively
The strcasecmp() function operates exactly like strcmp(), except that its comparison is
case insensitive. Its prototype follows:
int strcasecmp(string str1, string str2)
CHAPTER 9 ?–  S TRINGS AND REGULAR EXPRESS IONS 251
The following example compares two e-mail addresses, an ideal use for strcasecmp()
because case does not determine an e-mail address??™s uniqueness:
$email1 = "admin@example.com";
$email2 = "ADMIN@example.com";
if (! strcasecmp($email1, $email2))
echo "The email addresses are identical!";
?>
In this example, the message is output because strcasecmp() performs a caseinsensitive
comparison of $email1 and $email2 and determines that they are indeed
identical.
Calculating the Similarity Between Two Strings
The strspn() function returns the length of the first segment in a string containing
characters also found in another string. Its prototype follows:
int strspn(string str1, string str2)
Here??™s how you might use strspn() to ensure that a password does not consist solely
of numbers:
$password = "3312345";
if (strspn($password, "1234567890") == strlen($password))
echo "The password cannot consist solely of numbers!";
?>
In this case, the error message is returned because $password does indeed consist
solely of digits.


Pages:
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329