douxian0279 2012-03-06 17:51
浏览 199
已采纳

如何只获取数组中第一个匹配的值

Edit: I meant to ask what is the best/fastest way to get the first match or the first xx matches.

I have an array

$arr = ('abc', 'ded', 'kjld', 'abr', 'cdfd');

I want to shuffle this array first, and then retrieve ONLY the first value that matches the pattern /ab/. So, the returned value could be abc or abr.

I looked at preg_grep, but it will return an array of all the matches. Of course I could just retrieve the first value of the resultant array, but that is wasteful and requires an extra step of array manipulation. Is there another function or a preg_grep switch that specifies return only the first matched value (or first 5 matched values). I have looked at preg_match and preg_search, but they don't seem to give what I want.

  • 写回答

2条回答 默认 最新

  • douyao7390 2012-03-06 17:57
    关注

    You can loop through your array and end the loop when you find a match using break:

    foreach($arr as $value) {
        if(preg_match($pattern,$value)) {
            $return_string=$value;
            break;
        }
    }
    

    To specify a limit:

    $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;
    }
    

    You can then use another foreach loop to return your values like:

    if(count($results)>0)
    foreach ($results as $result) {
        echo $result;
    } else echo "No results found";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)