Core Function StrNatCmp
From Sputnik Wiki
StrNatCmp( <str1>, <str2>, <ignoreCase> )
Contents |
Description
String comparisons using a "natural order" algorithm.
Parameters
str1
The first string.
str2
The second string.
ignoreCase
Optional; Do case insensitive match
true = Ignore case and match case insensitively
false = Case must be an exact match
Return Value
Similar to other string comparison functions, this one returns
-1 if str1 is less than str2
1 if str1 is greater than str2
0 if they are equal.
Remarks
None.
Example
echo (StrNatCmp("Hello", "Hello") . "\n"); echo (StrNatCmp("Hello", "HellO") . "\n"); echo (StrNatCmp("Hello", "HellO", true) . "\n"); echo (StrNatCmp("HellO", "Hello") . "\n"); echo (StrNatCmp("HellO", "Hello", true) . "\n"); $arr = array("img12.png", "img10.png", "img2.png", "img1.png"); foreach($arr as $i) { foreach($arr as $j) { echo("First '$i' Second '$j' Code '" . StrNatCmp($i, $j) . "'\n"); } } /* 0 1 0 -1 0 First 'img12.png' Second 'img12.png' Code '0' First 'img12.png' Second 'img10.png' Code '1' First 'img12.png' Second 'img2.png' Code '1' First 'img12.png' Second 'img1.png' Code '1' First 'img10.png' Second 'img12.png' Code '-1' First 'img10.png' Second 'img10.png' Code '0' First 'img10.png' Second 'img2.png' Code '1' First 'img10.png' Second 'img1.png' Code '1' First 'img2.png' Second 'img12.png' Code '-1' First 'img2.png' Second 'img10.png' Code '-1' First 'img2.png' Second 'img2.png' Code '0' First 'img2.png' Second 'img1.png' Code '1' First 'img1.png' Second 'img12.png' Code '-1' First 'img1.png' Second 'img10.png' Code '-1' First 'img1.png' Second 'img2.png' Code '-1' First 'img1.png' Second 'img1.png' Code '0' */
Example of using this function to sort an array
$arr = array("img12.png", "img10.png", "img2.png", "img1.png"); say "Without sorting"; printr($arr); sort($arr, 1, Function( $a, $b ){ return StrNatCmp($a, $b, true); }); say "After natural sorting"; printr($arr); /* Without sorting ARRAY { [0] => img12.png [1] => img10.png [2] => img2.png [3] => img1.png } After natural sorting ARRAY { [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png } */