Jam*_*mex 3 php arrays pattern-matching
编辑:我想问一下获得第一场比赛或第一场比赛的最佳/最快方式是什么.
我有一个阵列
$arr = ('abc', 'ded', 'kjld', 'abr', 'cdfd');
Run Code Online (Sandbox Code Playgroud)
我首先想要shuffle这个数组,然后只检索与模式匹配的第一个值/ab/.因此,返回的值可以是abc或abr.
我看了看preg_grep,但它将返回所有比赛的数组.当然,我可以只检索结果数组的第一个值,但这很浪费,需要额外的数组操作步骤.是否有另一个函数或preg_grep开关指定仅返回第一个匹配的值(或前5个匹配的值).我已经看过preg_match和preg_search,但他们似乎不给我想要的东西.
使用break以下命令找到匹配项时,可以循环遍历数组并结束循环:
foreach($arr as $value) {
if(preg_match($pattern,$value)) {
$return_string=$value;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
要指定限制:
$limit=3;
$i=0 // sets the number of returned results to 0
$results=array();
foreach($arr as $value) {
if(preg_match($pattern,$value)) {
// add the result into the array and increment the counter
array_push($results,$value);
$i++;
} if ($i=$limit) break;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用另一个foreach循环返回您的值,如:
if(count($results)>0)
foreach ($results as $result) {
echo $result;
} else echo "No results found";
Run Code Online (Sandbox Code Playgroud)