0

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!

2 Answers2

1

Yeah, might be the problem since this function is binary unsafe. Can you try with strncasecmp ?

Take look also here - Sort an array with special characters in PHP, maybe you will find something what brings you some solution.

kamil.w
  • 134
  • 1
  • 5
  • Hi, @kamil.w! strcasecmp works fine, but it sorts not in natural order. – Alexander Popov May 10 '20 at 10:36
  • Hi @Alexander Popov. Good that you've resolved your problem. Anyway right now you also know what was the reason that native function didnt work (binary unsafe function, chars are from outside basic utf code:)) – kamil.w May 10 '20 at 18:24
0

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.