Usage analysis of php character comparison functions similar_text strnatcmp and strcasecmp

  • 2021-08-03 09:39:00
  • OfStack

In this paper, the usage of php character comparison functions similar_text, strnatcmp and strcasecmp are described with examples. Share it for your reference. The details are as follows:

The similar_text () function calculates the number of matching characters between two strings, and it can also calculate the similarity between two strings as a percentage.

Syntax: similar_text (string1, string2, percent)

Note: The levenshtein () function is faster than the similar_text () function, however, the similar_text () function provides more accurate results with fewer necessary modifications.

Let's look at the example. The code is as follows:

$str1="hello world";          // Definition string 1 
$str2="hello peter";          // Definition string 2
$result=similar_text($str1,$str2);       // Make a comparison
echo $result;  // Output the result after comparison

The strnatcmp () 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 function returns:

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

Syntax: strnatcmp (string1, string2).

Note: This function is case sensitive.

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

The strcasecmp () 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: strcasecmp (string1, string2)

Note: This function is binary-safe and case-insensitive. The code is as follows:

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

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


Related articles: