Skip to content

Instantly share code, notes, and snippets.

@Mika-
Created April 5, 2019 05:16
Show Gist options
  • Save Mika-/aa44054f28d4fa8842fa3792357c6a1e to your computer and use it in GitHub Desktop.
Save Mika-/aa44054f28d4fa8842fa3792357c6a1e to your computer and use it in GitHub Desktop.
<?php
/**
* Sort array of string by relevance
*
* @param array $array
* @param string $query
* @return array
*/
function array_sort_suggest(array $array, string $query) : array
{
uasort($array, function (string $a, string $b) use ($query) {
$aScore = 0;
$bScore = 0;
// Direct match
if ($a === $query) {
$aScore += 4;
}
if ($b === $query) {
$bScore += 4;
}
// Prefix match
if (!$aScore && preg_match('/^' . $query . '/i', $a)) {
$aScore += 3;
}
if (!$bScore && preg_match('/^' . $query . '/i', $b)) {
$bScore += 3;
}
// Substring prefix match
if (!$aScore && preg_match('/\b' . $query . '/i', $a)) {
$aScore += 2;
}
if (!$bScore && preg_match('/\b' . $query . '/i', $b)) {
$bScore += 2;
}
// Sort alphabetically if even score
if ($aScore === $bScore) {
return strcasecmp($a, $b);
}
return $bScore <=> $aScore;
});
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment