检查数组项是否存在正则表达式匹配 [英] Check if array key exists that matches regex

查看:173
本文介绍了检查数组项是否存在正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个快速(ER)的方法来检查,如果一个数组项是否存在一个模式相匹配?我的目标是用一个关键的以歌曲_ 开始,不管它如何结束的值。

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

目前我在做这样的:

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]}";
       }
   }           
}

有没有一种方法,以跨数组a preg_match,或者是的foreach array_keys 最原生的方式来做到这一点?

Is there a way to to a preg_match across arrays, or is foreach through array_keys the most native way to do that?

推荐答案

如何使用 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
# )

这篇关于检查数组项是否存在正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆