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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)