Created
August 2, 2012 13:02
-
-
Save mbunge/3236879 to your computer and use it in GitHub Desktop.
preg_match over given array with a defined pattern
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 | |
/** | |
* 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