【问题标题】:Check if array key exists that matches regex检查是否存在与正则表达式匹配的数组键
【发布时间】:2014-10-03 06:21:08
【问题描述】:

是否有一种快速(er) 的方法来检查是否存在与模式匹配的数组键?我的目标是使用以“song_”开头的键的值,无论它如何结束。

目前我正在这样做:

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

有没有办法跨数组进行 preg_match,或者foreacharray_keys 是最原生的方法?

【问题讨论】:

  • $r 中通常有多少个元素?其中有多少以song_ 开头?

标签: php arrays regex string


【解决方案1】:

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
# )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 2019-04-20
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2015-01-22
    相关资源
    最近更新 更多