phpcyrillicnatsort

natsort and strnatcasecmp work different with cyrillic


strnatcasecmp works very strange with cyrillic. See code:

//must be exact in this order
$s1 = 'Журнал 1';
$s2 = 'Каротаж';

$arr[] = $s1;
$arr[] = $s2;
natsort($arr);
//worked fine
var_dump($arr);

var_dump(strnatcasecmp($s1, $s2));
//returns 1 although must return -1!

Solution

  • Eventually, I resolved the problem like this:

    function strnatcasecmp_cyr($s1, $s2)
    {
        if ($s1 === $s2) {
            return 0;
        }
        $arr[] = $s1;
        $arr[] = $s2;
        natsort($arr);
        if (current($arr) === $s1) {
            return -1;
        } else {
            return 1;
        }
    }
    

    Pretty ugly, but it did the trick. Look forward for better solution.