astrakid932
astrakid932

Reputation: 3405

PHP Regex to find images with specific src attribute

I have a variable with HTML source and I need to find images within the variable that contain images with specific src attributes.

For example my image:

<img src="/path/img1.svg">

I have tried the below but doesnt work, any suggestions?

$hmtl = '<div> some stuff <img src="/path/img1.svg"/> </div><div>other stuff</div>';
preg_match_all('/<img src="/path/img1.svg"[^>]+>/i',$v, $images);

Upvotes: 0

Views: 238

Answers (1)

You should make use of DOMDocument Class, not regular expressions when it comes to parsing HTML.

<?php
$html='<img src="/path/img1.svg">';
$dom = new DOMDocument;
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $tag) {
        echo $tag->getAttribute('src'); //"prints" /path/img1.svg
}

Upvotes: 2

Related Questions