如何使用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!
}
?>
如何使用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!
}
?>
$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_reduce
和preg_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];
文档
使用preg_grep函数
$array = preg_grep(
'/(my\n+string\n+)/i',
array( 'file' , 'my string => name', 'this')
);
$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
)
$items = array();
foreach ($haystacks as $haystack) {
if (preg_match($pattern, $haystack, $matches)
$items[] = $matches[1];
}
foreach
并不会因此变得特别耗费资源。 - Lightness Races in Orbit可能有点长,但我可以提供给你这个版本!
$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'
);