Sometimes you want to sort an array in PHP, but exclude certain words.
I once needed this to sort a list of artists and bands. It is very common for bandnames to have articles in front of them.
When sorting those, it feels more natural to leave those words out, so that “The Doors” would end up at the letter D, and not T.
This little PHP function will do natcasesort, but will leave out the english articles a, an, the, and the dutch articles de, het and een:
function sort_na($a, $prefix= '/^((d|th)e|an?|een|het)s*/i') { $n=0; foreach($a as $entry){ $b[$n]['name']=preg_replace($prefix,"",$entry); $b[$n]['name_no_prefix']=$entry; $n++; } $cmp=create_function('$x, $y', 'return strnatcasecmp($x["name"], $y["name"]);'); usort($b, $cmp); $n=0; foreach($b as $entry) { $c[$n]=$entry['name_no_prefix']; $n++; } return $c; } |