This article mainly introduces PHP commonly used string comparison function, the example summarizes the Substr_compare, strncasecmp, strncmp, strcoll and other commonly used functions, has a certain reference value, the need for friends can refer to the following
The substr_compare () function compares two strings from a specified starting length , and the function returns:
0-If two strings are equal, <0-if string1 (from start position) is less than string2,>0-if string1 (from start) is greater than string2.
Syntax: Substr_compare (string1,string2,startpos,length,case), the code is as follows:
$str 1= "Hello World"; Defines the string 1 $str 2= "Hello World"; Defines the string 2 $result =substr_compare ($str 1, $str 2,1,10); Perform a comparison operation Echo $result; Output results, 1
The strnatcasecmp () function uses a "natural" algorithm to compare two strings , in the natural algorithm, the number "2" is less than the number "10", in the computer sort, "2" is greater than "10", This is because "2" is greater than "10" the first number, the code is as follows:
$str 1= "Hello World"; Defines the string 1 $str 2= "Hello World"; Defines the string 2 $result =strnatcasecmp ($str 1, $str 2); Perform a comparison operation Echo $result; Output results, 0
The strncasecmp () function compares two strings, and the function returns:
0-If two strings are equal, <0-if string1 is less than string2,>0-if string1 is greater than string2.
Syntax: strncasecmp (string1,string2,length), the code is as follows:
$str 1= "Hello World"; Defines the string 1 $str 2= "Hello World"; Defines the string 2 $result =strncasemp ($str 1, $str 2,7); Perform a comparison operation Echo $result; Output results, 0
The strncmp () function compares two strings , and the function returns:
0-If two strings are equal, <0-if string1 is less than string2,>0-if string1 is greater than string2.
Syntax: strncmp (string1,string2,length), the code is as follows:
$str 1= "Hello World"; Defines the string 1 $str 2= "Hello World"; Defines the string 2 $result =strncmp ($str 1, $str 2,7); Perform a comparison operation Echo $result; Output results, 1
The strcoll () function compares two strings , and the function returns:
0-If two strings are equal, <0-if string1 is less than string2,>0-if string1 is greater than string2.
The comparison of strings varies according to local settings, A<a or A>a.
Syntax: Strcoll (STRING1,STRING2), the code is as follows:
$str 1= "Hello World"; Defines the string 1 $str 2= "Hello World"; Defines the string 2 $result =strcoll ($str 1, $str 2); Perform a comparison operation Echo $result; Output results, 1