[英]PHP get image url from html-string using regular expression
I'm trying to get all images urls from a html-string with php.我正在尝试使用 php 从 html 字符串中获取所有图像 url。 Both from img-tags and from inline css (background-image)来自 img-tags 和内联 css (背景图像)
<?php
$html = '
<div style="background-image : url(https://exampel.com/media/logo.svg);"></div>
<img src="https://exampel.com/media/my-photo.jpg" />
<div style="background-image:url('https://exampel.com/media/icon.png');"></div>
';
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>|background-image[ ]?:[ ]?url\([ ]?[\']?["]?(.*?\.(?:png|jpg|jpeg|gif|svg))/i', $html, $image);
echo('<pre>'.print_r($image, true).'</pre>');
?>
The output from this is: output 是:
Array
(
[0] => background-image : url(https://exampel.com/media/logo.svg
[src] =>
[1] =>
[2] => https://exampel.com/media/logo.svg
)
Prefered output would be:首选 output 将是:
Array
(
[0] => https://exampel.com/media/logo.svg
[1] => https://exampel.com/media/my-photo.jpg
[2] => https://exampel.com/media/icon.png
)
I'm missing something here but I cant figure out what我在这里遗漏了一些东西,但我不知道是什么
Use preg_match_all() and rearrange your result:使用 preg_match_all() 并重新排列您的结果:
<?php
$html = <<<EOT
<div style="background-image : url(https://exampel.com/media/logo.svg);"></div>
<img src="https://exampel.com/media/my-photo.jpg" />
<div style="background-image:url('https://exampel.com/media/icon.png');"></div>
EOT;
preg_match_all(
'/<img.+src=[\'"](.+?)[\'"].*>|background-image ?: ?url\([\'" ]?(.*?\.(?:png|jpg|jpeg|gif|svg))/i',
$html,
$matches,
PREG_SET_ORDER
);
$image = [];
foreach ($matches as $set) {
unset($set[0]);
foreach ($set as $url) {
if ($url) {
$image[] = $url;
}
}
}
echo '<pre>' . print_r($image, true) . '</pre>' . PHP_EOL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.