简体   繁体   中英

PHP get image url from html-string using regular expression

I'm trying to get all images urls from a html-string with php. Both from img-tags and from inline css (background-image)

<?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:

Array
(
    [0] => background-image : url(https://exampel.com/media/logo.svg
    [src] => 
    [1] => 
    [2] => https://exampel.com/media/logo.svg
)

Prefered output would be:

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:

<?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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM