PHP 限制 foreach 循环中的项目

PHP limit items within a foreach loop

我正在尝试限制 foreach 循环中的项目数。我正在检查一个字符串是否包含 URL,如果是,则检查 JPG 扩展名。由于给出了多个结果,我想将这些结果限制为 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

我得到一个错误"Warning: Invalid argument supplied for foreach()"

我认为不需要第二个 foreach 循环。

下面应该让你第一个找到.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;   
   }
}

希望对您有所帮助!

foreach($match[0] as $link) 

报错。我认为问题是 foreach 需要一个数组,但 $match[0] 只是一个值。