php Common String Comparison Function Instances Summary

  • 2021-08-05 09:21:19
  • OfStack

This article summarizes the common string comparison functions of php. Share it for your reference. The specific analysis is as follows:

The substr_compare () function compares two strings from the specified starting length and returns:

0-If two strings are equal, < 0-If string1 (from the starting position) is smaller than string2, > 0-If string1 (from the starting position) is greater than string2.

Syntax: substr_compare (string1, string2, startpos, length, case) with the following code:

$str1="hello world";          // Definition string 1 
$str2="hello world";          // Definition string 2
$result=substr_compare($str1,$str2,1,10);      // Perform a comparison operation
echo $result;           // Output results, 1

The strnatcasecmp () function compares two strings using a "natural" algorithm in which the number "2" is less than the number "10" and in computer sorting, "2" is greater than "10" because "2" is greater than the first number of "10". The code is as follows:
$str1="hello world";          // Definition string 1 
$str2="hello world";          // Definition string 2
$result=strnatcasecmp($str1,$str2);       // Perform a comparison operation
echo $result;           // Output results, 0

The strncasecmp () function compares two strings and returns:

0-If two strings are equal, < 0-If string1 is smaller than string2, > 0-If string1 is greater than string2.

Syntax: strncasecmp (string1, string2, length), code as follows:

$str1="hello world";          // Definition string 1 
$str2="hello world";          // Definition string 2
$result=strncasemp($str1,$str2,7);       // Perform a comparison operation
echo $result;           // Output results, 0

The strncmp () function compares two strings and 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) with the following code:

$str1="hello world";          // Definition string 1 
$str2="hello world";          // Definition string 2
$result=strncmp($str1,$str2,7);        // Perform a comparison operation
echo $result;           // Output results, 1

The strcoll () function compares two strings and returns:

0-If two strings are equal, < 0-If string1 is smaller than string2, > 0-If string1 is greater than string2.

The comparison of strings will change according to local settings, a < a or a > a.

Syntax: strcoll (string1, string2), code as follows:

$str1="hello world";          // Definition string 1 
$str2="hello world";          // Definition string 2
$result=strcoll($str1,$str2);        // Perform a comparison operation
echo $result;           // Output results, 1

I hope this article is helpful to everyone's PHP programming.


Related articles: