PHP uses a "natural" algorithm to compare two strings (case-insensitive) function strnatcasecmp ()

Source: Internet
Author: User

Instance

Use the "natural" algorithm to compare two strings (case insensitive):

<?phpecho strnatcasecmp ("2Hello world!", "10Hello world!"); echo "<br>", Echo strnatcasecmp ("10Hello world!", "2Hello world!"); >

Definition and usage

The strnatcasecmp () function uses a "natural" algorithm to compare two strings (case insensitive).

In natural algorithms, the number 2 is less than the number 10. In computer sequencing, 10 is less than 2, because the first number in 10 is less than 2.

Note: strnatcasecmp () is case insensitive.

Grammar

STRNATCASECMP (STRING1,STRING2)
Parameters Describe
String1 Necessary. Specifies the first string to compare.
string2 Necessary. Specifies a second string to compare.

Technical details

return value: This function returns:
  • 0-if two strings are equal

  • <0-if string1 is less than string2

  • >0-if string1 is greater than string2

php version: 4+

More examples

Example 1

The difference between the natural algorithm (STRNATCMP) and the regular computer string sorting algorithm (strcmp):

<?PHP$ARR1 = $arr 2 = Array ("Pic1", "Pic2", "PIC10", "pic01", "pic100", "Pic20", "Pic30", "pic200"); echo "Standard string Comparison "." <br> "; Usort ($arr 1," strcmp ");p Rint_r ($arr 1); echo" <br> "; echo" Natural order string comparison "." <br> "; Usort ($arr 2," strnatcmp ");p Rint_r ($arr 2);? >

Natural Sort strnatcmp (): This function is basically the same as the strcmp function usage, but the principle of comparison is different. The function is not arranged in dictionary order, but rather the string is compared by "natural sort". The so-called natural sort is sorted according to people's Habits, For example, the strcmp function to sort, "4" would be greater than "14", while in reality, the number "14" is greater than "4", so the STRNATCMP function is compared by the latter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.