Search code examples
phploopsforeachpreg-match-allstrpos

PHP limit items within a foreach loop


I am trying to limit the number of items within a foreach loop. I am checking a string if it contains a URL, and if so, then check for a JPG extension. Since multiple results are given, I would like to limit those to just 1:

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $mystring, $match);

  foreach ($match[0] as $link){

     $strpos = strpos($link, '.jpg');
      if ($strpos !== false){
        $i_img = 0;
          foreach ($link as $imageurl){
            if ($i_img == 1) break;
              echo '</br>'.$imageurl;
              $i_img++;
          } // end foreach
       } // end if strpos

  } // end foreach

I get an error "Warning: Invalid argument supplied for foreach()"


Solution

  • I do not think there is a need for the second foreach loop.

    The following should get you the first found .jpg

    <?php
    
    //Test string
    $mystring = 'https://image.jpg, https://second.jpg';
    
    preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $mystring, $match);
    
    foreach ($match[0] as $link){
       $strpos = strpos($link, '.jpg');
       if ($strpos !== false){
           //do something meaningful here.
           echo $link; //https://image.jpg
           break;   
       }
    }
    

    Hope that helps!