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_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);
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)
文档
$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)
$array = preg_grep(
'/(my\n+string\n+)/i',
array( 'file' , 'my string => name', 'this')
);
Run Code Online (Sandbox Code Playgroud)