Php string comparison function usage Summary (strcmp, strcasecmp, strnatcmp and strnatcasecmp), strcmpstrcasecmp
This document analyzes the usage of php string comparison functions. We will share this with you for your reference. The details are as follows:
You can use "=" to directly compare whether the strings are completely consistent, but sometimes you may need to perform more complex string comparisons, such as partial matching.
1. strcmp () function: Compares strings. It is case sensitive during comparison.
Declaration: strcmp (string str1, string str2)
This function compares two input string parameters. If the two strings are identical, 0 is returned. If str1 is after str2 in alphabetical order, a positive number is returned. If str1 is less than str2, returns a negative number.
Example:
<? Php $ a = "I want to fly"; $ B = "I want to climb"; $ back = strcmp ($ a, $ B); if ($ back> 0) echo '$ a is greater than $ B'; elseif ($ back <0) echo '$ a is less than $ B'; else echo '$ a is equal to $ B';?>
Output result:
$ A is greater than $ B
2. strcasecmp (): this function is basically the same as the strcmp function, but this function is case insensitive during comparison.
Example:
<? Php $ val1 = "Hello"; $ val2 = "hello"; if (strcasecmp ($ val1, $ val2) = 0) echo '$ val1 and $ val2 are the same (case-insensitive strings are ignored)';?>
Output result:
$ Val1 and $ val2 are the same (case-insensitive strings are ignored)
3. Natural sorting strnatcmp (): this function is basically the same as the strcmp function, but the comparison principles are different.. This function is not ordered in alphabetical order, but compared strings by "natural sorting. the so-called natural sorting is to sort according to people's habits, such as the strcmp function to sort, "4" will be greater than "14", but in reality, the number "14" is greater than "4", so the strnatcmp function is compared according to the latter.
4. strnatcasecmp (): this function is used in the same way as the strcasecmp function, but the function is case insensitive.