如何使用 preg_match 在数组中进行搜索?

66

如何使用preg_match在数组中进行搜索?

示例:

<?php
if( preg_match( '/(my\n+string\n+)/i' , array( 'file' , 'my string  => name', 'this') , $match) )
{
    //Excelent!!
    $items[] = $match[1];
} else {
    //Ups! not found!
}
?>
6个回答

196
在这篇文章中,我将为您提供三种不同的方法来完成您所要求的内容。实际上,我推荐使用最后一种方法,因为它最容易理解,并且在代码中非常整洁。
## 我如何查看与我的正则表达式匹配的数组元素?
有一个专门用于此目的的函数,即preg_grep。它将正则表达式作为第一个参数,数组作为第二个参数。
请参考下面的示例:
$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

输出

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

###文档
##但是我只想获取指定组的值。怎么办?
使用array_reducepreg_match可以以简洁的方式解决这个问题;请参考下面的代码片段。
$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher ($m, $str) {
  if (preg_match ('/^hello (\w+)/i', $str, $matches))
    $m[] = $matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

输出

Array
(
    [0] => stackoverflow
    [1] => world
)

文档


###使用array_reduce似乎很繁琐,还有其他方法吗?
是的,实际上还有一种更简洁的方法,尽管它不涉及使用任何现有的array_*preg_*函数。
如果您打算多次使用此方法,请将其封装在一个函数中。
$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', $str, $m))
    $matches[] = $m[1];

文档


1
有人刚刚给这个帖子点了踩,我可以问一下背后的原因吗?上面的内容是正确的,也是OP所要求的,请解释一下。 - Filip Roséen - refp
4
不是我,这是对一个低质量问题的好回答。不过你应该停止滥用逗号 >.< - Lightness Races in Orbit
3
“停止滥用逗号和连字符” - 这基本上是我在 ##c++ 频道收到的消息的 10%,哈哈,很酷,逗号超棒,耶!**:-D** - Filip Roséen - refp
1
太棒了的回答! - Calamity Jane

8

使用preg_grep函数

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

7
$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

输出:

Array
(
   [1] => say hello
   [2] => hello stackoverflow
   [3] => hello world
)

4

这似乎对于这个任务来说过于复杂了。你需要使用回调函数来删除不匹配的项。 - Galen

3
$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

@OlafErlandsen:怎么样?你需要以某种方式检查每个元素。foreach并不会因此变得特别耗费资源。 - Lightness Races in Orbit
但它没有像你指定的那样捕获第一个括号匹配。 - goat

0

可能有点长,但我可以提供给你这个版本!


$array = array (
    'tagid=1' => '1',
    "a" => "a", 
    "b" => "b", 
    "c" => "c",
    'tagid=2' => '2',
);

$regex = '/tagid=[0-9]+/i';

$tags = [];

foreach ($data as $key => $value) {
    if (preg_match($regex, $key)) {
        $tags[] = $value;
    }
}

// OUTPUT
$tags = array (
    0 => '1',
    1 => '2'
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接