2016-05-13 9 views
-1

私はイメージのための簡単なウェブスクレイピングをやっています。preg_matchの後に最初のいくつかの結果を取得します

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

$画像私は、foreachループ内で$ SRCを印刷する場合、私は再びHTTPが、それは11件の結果を示し、一致した後、$ srcを印刷する場合、それは19のresults.Fromこれらの19件の結果を示して

DOMNodeList Object 
(
    [length] => 19 
) 

を返します。しかし、私はpreg_match後の11の結果から最初の5つの結果が必要です。

どうすれば可能ですか?以下のコードで

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

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

    } 
} 

答えて

3

テスト

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

それは、あなたはすべての一致した結果を返すpreg_match機能に三番目のパラメータを渡すことができます最初の5の正規表現の一致するレコード

+0

正確には私が期待しています。 –

+0

@SubhankarBhattacharjee、答えも受け入れてください。 :) – Arun

+0

はい、承諾しました。 –

0

にあなたを与えるだろう

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]; 
    } 
} 
0

良いアプローチ「最初の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--; 
    } 
} 
関連する問題