I would like to sort strings in PHP, and the match should be done foremost on the first letters of a substring, then on the letters of the whole the string.
For example, if someone searches do
, and the list contains
Adolf
Doe
Done
the result should be
Doe
Done
Adolf
Using the regular sort($array, SORT_STRING)
or things like that does not work, Adolf is sorted before the others.
Does someone have an idea how to do that ?
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
usort(array, callback)
lets you sort based on a callback.
example (something like this, didn't try it)
usort($list, function($a, $b) {
$posa = strpos(tolower($a), 'do');
$posb = strpos(tolower($b), 'do');
if($posa != 0 && $posb != 0)return strcmp($a, $b);
if($posa == 0 && $posb == 0)return strcmp($a, $b);
if($posa == 0 && $posb != 0)return -1;
if($posa != 0 && $posb == 0)return 1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With