Prev | Current Page 316 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Comparing Two Strings
String comparison is arguably one of the most important features of the string-handling
capabilities of any language. Although there are many ways in which two strings can
be compared for equality, PHP provides four functions for performing this task:
strcmp(), strcasecmp(), strspn(), and strcspn(). These functions are discussed in the
following sections.
Comparing Two Strings Case Sensitively
The strcmp() function performs a binary-safe, case-sensitive comparison of two strings.
Its prototype follows:
int strcmp(string str1, string str2)
250 CHAPTER 9 ?–  STRINGS AND REGULAR EXPRESSIONS
It will return one of three possible values based on the comparison outcome:
??? 0 if str1 and str2 are equal
??? -1 if str1 is less than str2
??? 1 if str2 is less than str1
Web sites often require a registering user to enter and then confirm a password,
lessening the possibility of an incorrectly entered password as a result of a typing
error. strcmp() is a great function for comparing the two password entries because
passwords are often case sensitive:
$pswd = "supersecret";
$pswd2 = "supersecret2";
if (strcmp($pswd,$pswd2) != 0)
echo "Passwords do not match!";
else
echo "Passwords match!";
?>
Note that the strings must match exactly for strcmp() to consider them equal. For
example, Supersecret is different from supersecret. If you??™re looking to compare two
strings case insensitively, consider strcasecmp(), introduced next.


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