Home > Mobile >  PHP get image url from html-string using regular expression
PHP get image url from html-string using regular expression

Time:01-21

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

CodePudding user response:

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;
  •  Tags:  
  • Related