0

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);
2

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

As an alternative, you can create a new DOMXPath object and do an xpath query for //img[@src='foo']
I have updated the question. I am trying to get all images with a specific image src from some sourcecode, not just the src from img
Thanks for modifying the question late.. (I personally hate that :P) Anyways..That example is not enough , Can you post your HTML content and show us your expected output ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.