Skip to content

Instantly share code, notes, and snippets.

@mbunge
Created August 2, 2012 13:02
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbunge/3236879 to your computer and use it in GitHub Desktop.
preg_match over given array with a defined pattern
<?php
/**
* preg_match over given array with a defined pattern
*
* Example:
*
* $names = array(
* 'hans',
* 'dieter',
* 'peter',
* 'gnthr' => 'günther',
* 'jürgen',
* 'jens',
* 'dietmar'
* );
*
* preg_match_array('/^j/', $names);
*
* returns an array with names which are beginning
*
* @param $pattern
* @param array $subjectArray
* @param array $allMatches
* @param null $flags
* @param null $offset
*
* @see preg_match
* @return array
*/
function preg_match_array($pattern, array $subjectArray, &$allMatches = array(), $flags = null, $offset = null)
{
$results = array();
$allMatches = array();
array_walk($subjectArray, function($subject, $key) use($pattern, $flags, &$allMatches, $offset, &$results)
{
if (preg_match($pattern, $subject, $matches, $flags, $offset))
$results[$key] = $subject;
$allMatches[$key] = $matches;
});
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment