As the others have said, usort
and a bespoke comparator would fit well. Here's an example which has a factory function (in this case, a function which returns a function) which generates comparators (using closures) based on the required prefix.
$subject = explode(',', 'london,bluehit,green,lonpark,abc,aab,lonsee');
function make_comparator($prefix)
{
return function ($a, $b) use ($prefix) {
if (strpos($a, $prefix) === 0 && strpos($b, $prefix) !== 0) {
// $a starts with $prefix (and $b does not), sift up
return -1;
} elseif (strpos($a, $prefix) !== 0 && strpos($b, $prefix) === 0) {
// $b starts with $prefix (and $a does not), sift down
return 1;
} else {
// Otherwise, do a normal string comparison
return strcmp($a, $b);
}
};
}
$sorted = $subject;
usort($sorted, make_comparator('lon'));
var_dump($sorted);
For PHP versions less than 5.3.0 (required for above) you could do something similar:
function prefix_comparator($a, $b, $prefix) {
if (strpos($a, $prefix) === 0 && strpos($b, $prefix) !== 0) {
// $a starts with $prefix (and $b does not), sift up
return -1;
} elseif (strpos($a, $prefix) !== 0 && strpos($b, $prefix) === 0) {
// $b starts with $prefix (and $a does not), sift down
return 1;
} else {
// Otherwise, do a normal string comparison
return strcmp($a, $b);
}
}
$sort_by_lon = create_function('$a, $b', 'return prefix_comparator($a, $b, "lon");');
$sorted = $subject;
usort($sorted, $sort_by_lon);
var_dump($sorted);
(Apologies for the jargon)