PHP 从字符串中获取图像的所有 URL

Bri*_*ica 6 php regex string url image

我需要一个用于 PHP 的函数或正则表达式字符串,我可以像这样传递一个字符串:

Lorem ipsum dolor 坐 amet,http ://www.gettyimages.com/images/marketing/frontdoorStill/PanoramicImagesRM/FD_image.jpg consectetur adipiscing elit。Nullam sed diam lectus,一种 rutrum orci。暂停潜力。Nulla facilisi。暂停潜力。Ut http://www.handsonuniverse.org/get_images/images/20090802.ngc6992.HOS.jpg ullamcorper mauris 坐 amet elit tristique 坐 amet laoreet nunc 调味品。Lorem ipsum dolor 坐 amet,consectetur adipiscing 精英。Aliquam euismod arcu non odio http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg aliquam 前庭。Sed eleifend Tellus id augue luctus ac ultrices leo semper。

我会得到回报:

http://www.gettyimages.com/images/marketing/frontdoorStill/PanoramicImagesRM/FD_image.jpg http://www.handsonuniverse.org/get_images/images/20090802.ngc6992.HOS.jpg http://www.prelovac。 com/vladimir/wp-content/uploads/2008/03/example.jpg

在一个数组中。我需要它根据天气获取 URL,或者它们是否包含常规图像扩展名,例如 *.jpg、*.png、*.bmp 等。有人知道存在的一个,这样我就可以避免重新发明轮子吗?谢谢!

Lon*_*erd 6

好吧,下面将适用于您的示例:

preg_match_all('/(https?:\/\/\S+\.(?:jpg|png|gif))\s+/', $content, $matches);
Run Code Online (Sandbox Code Playgroud)

添加您想要捕获的任何其他扩展。

请注意,上述内容不一定稳健(www.blah.com/image.jpg例如,它不会匹配)。它也不会匹配不以扩展名结尾的 URL,即使它们是图像(即,http://domain.com/blah.jpg?loadsmall=true或其他东西)。有很多方法可以使它更智能,但这实际上取决于您期望的输入类型,因为这将决定您的解析需要有多复杂。


Saj*_*ake 5

如果您不想使用正则表达式来执行此操作。相反,解析 HTML。

\n\n
<?php\n$html='YOUR_STRING';\n$dom = new domDocument; \n$dom->loadHTML($html); \n$dom->preserveWhiteSpace = false;\n$images = $dom->getElementsByTagName('img');\n\nforeach ($images as $image) \n   {   \n     echo $image->getAttribute('src'); \n   }\n\n?>\n
Run Code Online (Sandbox Code Playgroud)\n