2 回答
TA贡献1798条经验 获得超7个赞
这里有两个例子。您可以使用函数提前返回,或者中断循环。请注意,这两种方法都会在第一次匹配后短路。
<?php
$arrayDirectors = array("Fellini","Ray","Hitchcock");
$arrayMovies = array("La Dolce Vita","East of Eden","North by Northwest");
function keyword_search($keyword, $array) {
foreach($array as $value)
if (preg_match("/\b" . preg_quote($keyword) . "/i", $value))
return true;
}
if(keyword_search('Hitch', $arrayDirectors))
echo 'Search term found in directors.';
输出:
Search term found in directors.
要查找您获得匹配的集合:
<?php
foreach(['directors' => &$arrayDirectors, 'movies' => &$arrayMovies] as $collection => $v)
{
if(keyword_search('eden', $v)) {
$matched = $collection;
break;
}
}
echo $matched;
输出:
movies
我在您的正则表达式中添加了一个单词边界,否则很容易过早匹配/或过度匹配恕我直言。
但您可能想要匹配多个标题。在这种情况下,您可能想要过滤数组:
<?php
$arrayMovies = array("North to Alaska","East of Eden","North by Northwest","Westworld");
function keyword_filter($keyword, $array) {
return array_filter($array, function($value) use ($keyword) {
return preg_match("/\b" . preg_quote($keyword) . "/i", $value);
});
}
var_export(keyword_filter('north', $arrayMovies));
echo "\n";
var_export(keyword_filter('west', $arrayMovies));
输出:
array (
0 => 'North to Alaska',
2 => 'North by Northwest',
)
array (
3 => 'Westworld',
)
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报