在PHP中是否可以从字符串的开头获取图像URL?

在PHP中是否可以从字符串的开头获取图像URL?,php,regex,image,parsing,Php,Regex,Image,Parsing,我有一个示例字符串,如下所示 $string = ' http://image.gsfc.nasa.gov/image/image_launch_a5.jpg http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg http://image.gsfc.nasa.gov/image/image_launch_a5.jpg Alot of text http://www.google.com/i

我有一个示例字符串,如下所示

$string = '
http://image.gsfc.nasa.gov/image/image_launch_a5.jpg
http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg
http://image.gsfc.nasa.gov/image/image_launch_a5.jpg

Alot of text

http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif

more text';
我希望能够将前三个图像的url(基本上是字符串开头的任何图像)外置,但在非图像文本启动后不提取任何图像url。我可以成功地使用regex抓取所有图像URL,但它也抓取了文本中的最后一张google.com图像


谢谢你的建议

让R是regex来获取图像url

您需要获取(R)+,即0个或更多的R

或者主要是((R)(w)?)+


其中w表示匹配空格的正则表达式。

如何避免使用正则表达式,而改用
explode

$string = '....';

$urls = array();
$lines = explode(PHP_EOL,$string);
foreach ($lines as $line){
  $line = trim($line);

  // ignore empty lines
  if (strlen($line) === 0) continue;

  $pUrl = parse_url($line);

  // non-valid URLs don't count
  if ($pUrl === false) break;

  // also skip URLs that aren't images
  if (stripos($pUrl['path'],'.jpg') !== (strlen($pUrl['path']) - 4)) break;

  // anything left is a valid URL and an image
  // also, because a non-url fails and we skip empty lines, the first line
  // that isn't an image will break the loop, thus stopping the capture
  $urls[] = $line;
}
var_dump($urls);

位于

的示例没有花费精力编写正则表达式,因为您已经说过可以成功地使用regex获取所有图像URL:)尝试搜索。这是以前做过的。很多次。然而,如果你能抓取全部(如文章中所说),那么这仅仅是一小步:1)在X之后停止抓取(改变你已有的方法)或2)抓取N,然后只“采取/使用”X(使用你已有的方法,只使用结果数据的一个子集)@pst N未知,字符串开始时可能有1个图像或10个图像,这是我的问题,否则我会通过一个简单的regexSee#1和#2获取前3个。它们不会改变。调整你的想法。有趣的是,我真的很喜欢这个想法,我刚刚插入了它,但现在它抓住了每一行:(@Mark:很抱歉,请尝试一下(答案已更新)。我还利用
parse_url
验证了图像url。