In PHP, string comparison is a very common operation. Usually we use strcmp() or strcasecmp() functions to compare the size and equality of two strings, but both functions are compared character by character according to the ASCII value of the letter, while strnatcasecmp() function is compared in a "natural sort" way, while ignoring case.
This article will explain in detail how to use PHP's strnatcasecmp() function to ignore case comparison of two strings, and explain how it differs from other comparison functions.
strnatcasecmp() is a built-in function in PHP. It is full name "string natural case-insensitive comparison". It compares two strings according to "natural order" and ignores upper and lower case.
The so-called "natural sorting" means that the number parts will be compared as numbers, rather than simply character-by-character comparison. For example, the string "file10.txt" will be considered greater than "file2.txt" because the number 10 is greater than 2, not because the character "1" is greater than 2.
int strnatcasecmp ( string $str1 , string $str2 )
$str1 and $str2 : Two strings to compare.
Return value:
If $str1 is less than $str2 , a negative number is returned.
If the two strings are equal, return 0.
If $str1 is greater than $str2 , a positive number is returned.
<?php
$str1 = "File10.txt";
$str2 = "file2.txt";
$result = strnatcasecmp($str1, $str2);
if ($result < 0) {
echo "'$str1' Less than '$str2'";
} elseif ($result > 0) {
echo "'$str1' Greater than '$str2'";
} else {
echo "'$str1' and '$str2' equal";
}
?>
Output:
'File10.txt' Greater than 'file2.txt'
Here, although the number part of the first string is "10" and the second is "2", strnatcasecmp() correctly recognizes the size of the number and ignores case.
Function name | Whether it is case sensitive | Whether to sort naturally | illustrate |
---|---|---|---|
strcmp() | yes | no | Case sensitive, character comparison |
strcasecmp() | no | no | Case-insensitive, character-by-character comparison |
strnatcmp() | yes | yes | Case sensitive, natural sorting |
strnatcasecmp() | no | yes | Insensitive to case, natural sorting |
Suppose you want to compare the path parts of the two URLs based on the file name and ignore the case and numeric size relationship, you can use strnatcasecmp() to achieve it.
<?php
$url1 = "https://gitbox.net/files/File10.txt";
$url2 = "https://gitbox.net/files/file2.txt";
// Analysis URL,Take the path part
$path1 = parse_url($url1, PHP_URL_PATH);
$path2 = parse_url($url2, PHP_URL_PATH);
// use strnatcasecmp Compare paths
if (strnatcasecmp($path1, $path2) < 0) {
echo "$path1 Less than $path2";
} elseif (strnatcasecmp($path1, $path2) > 0) {
echo "$path1 Greater than $path2";
} else {
echo "$path1 and $path2 equal";
}
?>
Output:
/files/File10.txt Greater than /files/file2.txt
This is very practical when dealing with strings with numbers, such as file names, version numbers, etc.