Check if array matching regular expression exists

Is there a quick (er) way to check if an array exists matching the pattern? My goal is to use the value of the key starting with " song_ ", no matter how it ends.

I am currently doing this:

 foreach($result as $r){ // $r = array("title"=>'abc', "song_5" => 'abc') $keys = array_keys($r); foreach($keys as $key){ if (preg_match("/^song_/", $key) { echo "FOUND {$r[$key]}"; } } } 

Is there a way for preg_match for arrays or foreach via array_keys most native way to do this?

+7
string arrays php regex
source share
1 answer

How about using preg_grep :

 $keys = ['song_the_first', 'title', 'song_5']; $matched = preg_grep('/^song_/', $keys); # print_r($matched) # # Array # ( # [0] => song_the_first # [2] => song_5 # ) 
+11
source share

All Articles