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

Jor*_*sen 50 php regex arrays preg-match

如何使用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!
}
?>
Run Code Online (Sandbox Code Playgroud)

Fil*_*efp 147

在这篇文章中,我将为您提供三种不同的方法来满足您的要求.我实际上建议使用最后一个片段,因为它最容易理解,并且在代码中非常整洁.

如何查看数组中与正则表达式匹配的元素?

有一个专门用于此目的的功能preg_grep.它将使用正则表达式作为第一个参数,将数组作为第二个参数.

见下面的例子:

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

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

print_r ($matches);
Run Code Online (Sandbox Code Playgroud)

产量

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)
Run Code Online (Sandbox Code Playgroud)

文档


但我只想获得指定组的值.怎么样?

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);
Run Code Online (Sandbox Code Playgroud)

产量

Array
(
    [0] => stackoverflow
    [1] => world
)
Run Code Online (Sandbox Code Playgroud)

文档


使用array_reduce看似乏味,是不是有另一种方式?

是的,虽然它不涉及使用任何预先存在的array_*preg_*功能,但这个实际上更干净.

如果要多次使用此方法,请将其包装在函数中.

$matches = array ();

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

文档

  • 不是我; 对于一个糟糕的问题,这是一个很好的答案.你应该停止滥用逗号,但是>.< (4认同)
  • @ TomalakGeret'kal"停止滥用逗号和连字符" - 这就是我在## c ++中收到的相当于10%的信息 - 哈哈,狗屎,酷,逗号很棒,是的!** - **d (3认同)

Mah*_*our 7

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

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

print_r($matches);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
   [1] => say hello
   [2] => hello stackoverflow
   [3] => hello world
)
Run Code Online (Sandbox Code Playgroud)


Gal*_*len 5

使用preg_grep

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