Skip to content

Instantly share code, notes, and snippets.

@nathggns
Created July 19, 2013 21:30
Show Gist options
  • Save nathggns/6042498 to your computer and use it in GitHub Desktop.
Save nathggns/6042498 to your computer and use it in GitHub Desktop.
Sort an array based on an array of regular expressions.
<?php
/**
* Search an array of regular expressions for the indexes that match a needle
*
* @param string $needle The needle
* @param array $haystack The array of regular expressions to search
* @param boolean $all Should it return all indexes or just the first one
* @return mixed boolean: false if no matches are found and $all
* equals false
*
* array: if $all is true, an array of indexes where
* there is a match, or an empty array if there
* are no matches.
*
* int: The index of the first matching regular expression
*/
function array_preg_search($needle, $haystack, $all = false)
{
$results = array();
foreach ($haystack as $index => $item) {
if (preg_match($item, $needle)) {
$results[] = $index;
if (!$all) break;
}
}
if ($all) {
return $results;
} else {
return count($results) === 1 ? $results[0] : false;
}
}
/**
* Sort an array based on an array of regular-expression keys
* @param array $haystack The array to sort
* @param array $order The order to sort them into
* @param function $secondary_sort The function to sort if both match
* the same index in the order array
* @return array The sorted array
*/
function array_preg_sort($haystack, $order, $secondary_sort = null)
{
uksort($haystack, function($a, $b) use ($order, $secondary_sort) {
$a_result = $this->array_preg_search($a, $order);
$b_result = $this->array_preg_search($b, $order);
if ($a_result < $b_result) {
return -1;
} else if ($a_result > $b_result) {
return 1;
} else if (isset($secondary_sort)) {
return call_user_func($secondary_sort, $a, $b);
} else {
return 0;
}
});
return $haystack;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment