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);
condo1234
  • 3,285
  • 6
  • 25
  • 34
  • [HTML is not a language that can be parsed by RegEx](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – Daedalus Mar 08 '14 at 07:55
  • You should escape each occurence of slash (`/`) inside your regex since it used as regex delimiter. – hindmost Mar 08 '14 at 08:03

1 Answers1

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
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • As an alternative, you can create a new `DOMXPath` object and do an xpath query for `//img[@src='foo']` – Maerlyn Mar 08 '14 at 07:58
  • 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 – condo1234 Mar 08 '14 at 08:00
  • 1
    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 ? – Shankar Narayana Damodaran Mar 08 '14 at 08:02