Natural sorting algorithm in PHP with support for Unicode?

后端 未结 5 1529
名媛妹妹
名媛妹妹 2020-12-05 00:47

Is it possible to sort an array with Unicode / UTF-8 characters in PHP using a natural order algorithm? For example (the order in this array is correctly ordered):



        
5条回答
  •  旧时难觅i
    2020-12-05 01:41

    Nailed it!

    $array = array('Ägile', 'Ãgile', 'Test', 'カタカナ', 'かたかな', 'Ágile', 'Àgile', 'Âgile', 'Agile');
    
    function Sortify($string)
    {
        return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1' . chr(255) . '$2', htmlentities($string, ENT_QUOTES, 'UTF-8'));
    }
    
    array_multisort(array_map('Sortify', $array), $array);
    

    Output:

    Array
    (
        [0] => Agile
        [1] => Ágile
        [2] => Âgile
        [3] => Àgile
        [4] => Ãgile
        [5] => Ägile
        [6] => Test
        [7] => かたかな
        [8] => カタカナ
    )
    

    Even better:

    if (extension_loaded('intl') === true)
    {
        collator_asort(collator_create('root'), $array);
    }
    

    Thanks to @tchrist!

提交回复
热议问题