Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort strings, first letters first, then letters inside words

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 ?

like image 417
user1603166 Avatar asked Aug 16 '12 12:08

user1603166


People also ask

How do I sort a string into characters?

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.


1 Answers

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;
});
like image 191
Roman Avatar answered Oct 21 '22 22:10

Roman