Home  >  Article  >  Backend Development  >  How to compare two strings in php

How to compare two strings in php

(*-*)浩
(*-*)浩Original
2019-10-08 10:37:024623browse

Common methods for string comparison in PHP

How to compare two strings in php

Compare by bytes

By word Section comparison of strings is the most common method. The functions that may be used are strcmp() and strcasecmp(). (Recommended learning: PHP Video Tutorial)

The difference between these two functions is that strcmp() distinguishes the case of characters, while strcasecmp() does not distinguish the case of characters. The usage of the two is basically same.

Only strcmp() is introduced here;

The syntax is as follows:

int strcmp(string str1,string str2)

The parameters str1 and parameter str2 are the two strings to be compared. If If they are equal, 0 is returned; if the parameter str1 is greater than str2, the return value is greater than 0; if the parameter str1 is less than str2, the return value is less than 0.

Comparison according to natural sorting method

In PHP, string comparison according to natural sorting method is implemented through the strnatcmp() function. The natural sorting method compares the numerical part of the string and sorts the numbers in the string according to size.

The syntax is as follows:

int strnatcmp(string str1,string str2)

The strnatcmp() function uses a "natural" algorithm to compare two strings.

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

The above is the detailed content of How to compare two strings in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn