Natural Order String Comparison
This function is binary-safe
This function is CASE SENSITIVE.
<?php
int strnatcmp ( str $str1 , str $str2 )
where,
$str1 = The first STRING to compare
$str2 = The second STRING to compare
?>
<?php
$strnccmp01a = "Better late than never!";
$strnccmp01b = "BETTER LATE THAN NEVER!";
$lenght01 = 6;
// 6 initial characters
$intnccmp01ab = strnatcmp($strnccmp01a,
$strnccmp01b);
if ($intnccmp01ab > 0)
{
echo substr($strnccmp01a, 0, $lenght01) .
'<br>is GREATER than<br>' .
substr($strnccmp01b, 0, $lenght01);
}
elseif ($intnccmp01ab < 0)
{
echo substr($strnccmp01a, 0, $lenght01) .
'<br>is LESS than<br>' .
substr($strnccmp01b, 0, $lenght01);
}
else
{
echo substr($strnccmp01a, 0, $lenght01) .
'<br>is EQUAL to<br>' .
substr($strnccmp01b, 0, $lenght01);
}
?>
<?php
$tst02 = glob('' . "*{.JPG,.jpg,.txt,.TXT,
.mp3,.MP3,
.wav,.WAV,
.m4a,.M4A}", GLOB_BRACE);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This code retrieves all files in the
specified directory, if they are:
.JPG,.jpg,.txt,.TXT,.mp3, .MP3, .wav, .WAV, .m4a, .M4A
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
usort($tst02, "strnatcmp");
foreach($tst02 as $ts02)
{
echo basename($ts02) . '<br>';
}
?>
<?php
echo "Testing strnatcmp() : basic functionality.<br>";
$a1 = "abc1";
$b1 = "abc10";
$c1 = "abc15";
$d1 = "abc2";
$a2 = "ABC1";
$b2 = "ABC10";
$c2 = "ABC15";
$d2 = "ABC2";
function str_natcmp($par01, $par02)
{
$natcmp = strnatcmp($par01, $par02);
if($natcmp > 0)
{
echo "<br>$par01<br>is GREATER than<br>$par02<br>";
}
elseif($natcmp == 0)
{
echo "<br>$par01<br>is EQUAL to<br>$par02<br>";
}
elseif($natcmp < 0)
{
echo "<br>$par01<br>is LESS than<br>$par02<br>";
}
}
echo "- - -<br>Less than tests:<br>";
str_natcmp($a1, $b1);
str_natcmp($a1, $c1);
str_natcmp($a1, $d1);
str_natcmp($b1, $c1);
str_natcmp($d1, $c1);
echo '<br>- - - <br><br>';
str_natcmp($a1, $b2);
str_natcmp($a1, $c2);
str_natcmp($a1, $d2);
str_natcmp($b1, $c2);
str_natcmp($d1, $c2);
echo "<br>- - - <br><br>Equal to tests;<br>";
str_natcmp($b1, $b1);
str_natcmp($b1, $b2);
echo "<br>- - - <br><br>Greater than tests:<br>";
str_natcmp($b1, $a1);
str_natcmp($c1, $a1);
str_natcmp($d1, $a1);
str_natcmp($c1, $b1);
str_natcmp($c1, $d1);
echo '<br>- - - <br><br>';
str_natcmp($b1, $a2);
str_natcmp($c1, $a2);
str_natcmp($d1, $a2);
str_natcmp($c1, $b2);
str_natcmp($c1, $d2);
?>
<?php
echo "Testing strnatcmp() function
whitespace, left-align, digit.";
echo "<br><br>Leading whitespace,
digits, string 1 longer:<br>";
$str1 = " 00";
$str2 = " 0";
var_dump( strnatcmp( $str1, $str2) );
echo "<br><br>Leading whitespace,
digits, string 2 longer:<br>";
var_dump( strnatcmp( $str2, $str1) );
?>