Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在赛前比赛后获得前几个结果_Php_Preg Match - Fatal编程技术网

Php 在赛前比赛后获得前几个结果

Php 在赛前比赛后获得前几个结果,php,preg-match,Php,Preg Match,我正在做一个简单的图像网页抓取 $images = $dom->getElementsByTagName('img'); $images返回 DOMNodeList Object ( [length] => 19 ) 如果我在foreach循环中打印$src,它将显示19个结果。如果我在http匹配后再次打印$src,它将显示这19个结果中的11个结果。但我想在赛前的11场比赛中得到前5场比赛的结果 怎么可能呢 foreach ($images as $keys=>$

我正在做一个简单的图像网页抓取

$images = $dom->getElementsByTagName('img');
$images返回

DOMNodeList Object
(
   [length] => 19
)
如果我在foreach循环中打印$src,它将显示19个结果。如果我在http匹配后再次打印$src,它将显示这19个结果中的11个结果。但我想在赛前的11场比赛中得到前5场比赛的结果

怎么可能呢

foreach ($images as $keys=>$image) {                

   $src = $image->getAttribute('src');
    if(preg_match('/^http/', $src)){

    }
}

使用下面的代码进行测试

$loopCount = 1;
foreach ($images as $keys=>$image) {                
   $src = $image->getAttribute('src');
    if(preg_match('/^http/', $src)) {
        //assuming here you need to check count
        $loopCount ++;
        //your action
        if($loopCount > 5) {
           break;  //to avoid unnecessary loops
        }
    }
}

它将为您提供前5个正则表达式匹配记录

您可以将第三个参数传递给
preg\u match
函数,该函数将返回所有匹配的结果

foreach ($images as $keys=>$image) {                

   $src = $image->getAttribute('src');
    $matches = [];
    if(preg_match('/^http/', $src,$matches)){   // pass third parameter 
                                  ^^ will store all matched results

       print_r($matches); // Will show all matched results
       // Now you can use any of matched results for `$matches`

       // just an example
       $data[] = $matches[0];
       $data[] = $matches[1];
       $data[] = $matches[2];
       $data[] = $matches[3]; 
       $data[] = $matches[4];
    }
}

如果获得“前5个结果”,则最好停止循环:

$count = 5;
foreach ($images as $keys => $image) {

   if (!count) break;   // avoid redundant loop iterations
   $src = $image->getAttribute('src');
   if (preg_match('/^http/', $src)) {
       // processing the image item
       $count--;
   }
}

如我所料。@Subbankarbhattacharjee,请也接受答案。:)