Created
April 5, 2019 05:16
-
-
Save Mika-/aa44054f28d4fa8842fa3792357c6a1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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