21

I would like to know how this can be achieved.

Assume: That there's a lot of html code containing tables, divs, images, etc.

Problem: How can I get matches of all occurances. More over, to be specific, how can I get the img tag source (src = ?).

example:

<img src="http://example.com/g.jpg" alt="" />

How can I print out http://example.com/g.jpg in this case. I want to assume that there are also other tags in the html code as i mentioned, and possibly more than one image. Would it be possible to have an array of all images sources in html code?

I know this can be achieved way or another with regular expressions, but I can't get the hang of it.

Any help is greatly appreciated.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Ahmad Fouad
  • 3,957
  • 14
  • 45
  • 62
  • possible duplicate of http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php and http://stackoverflow.com/questions/138839/how-do-you-parse-a-html-string-for-image-tags-to-get-at-the-src-information among others – Josh E Jul 28 '09 at 20:39

10 Answers10

41

While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.

What I recommend you do is use a DOM parser such as SimpleHTML and use it as such:

function get_first_image($html) {
    require_once('SimpleHTML.class.php')

    $post_html = str_get_html($html);

    $first_img = $post_html->find('img', 0);

    if($first_img !== null) {
        return $first_img->src;
    }

    return null;
}

Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.

A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression.

Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression:

<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>

And then again, the above can fail if:

  • The attribute or tag name is in capital and the i modifier is not used.
  • Quotes are not used around the src attribute.
  • Another attribute then src uses the > character somewhere in their value.
  • Some other reason I have not foreseen.

So again, simply don't use regular expressions to parse a dom document.


EDIT: If you want all the images:

function get_images($html){
    require_once('SimpleHTML.class.php')

    $post_dom = str_get_dom($html);

    $img_tags = $post_dom->find('img');

    $images = array();

    foreach($img_tags as $image) {
        $images[] = $image->src;
    }

    return $images;
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • I find this way very nice. This will work regardless of the attributes order correct? I mean src or SRC, will work? even if I put the alt and title tags..? This code will work on clients servers, so I need to make sure that whatever way they will put the src it will be extracted. Thanks so much for the fast and comlete answer. – Ahmad Fouad Jul 28 '09 at 20:48
  • 2
    **@Ahmad Fouad:** Correct, using a DOM Parser will work regarless of attribute order and capitalization. – Andrew Moore Jul 28 '09 at 20:50
  • why all the non-greedy "`\s*?`" in your regex? wouldn't plain-old greedy "`\s*`" be more efficient? – Kip Jul 28 '09 at 20:51
  • **@Kip:** Because you don't want it to be greedy. – Andrew Moore Jul 28 '09 at 20:54
  • Very nice. I think i will take this solution, because the users who posted regex, post various formulas and assume that the src will be entered in specific way and order.. this can become useless if the client put the src non-traditional way :( Thanks so much! – Ahmad Fouad Jul 28 '09 at 20:58
  • **@Ahmad Fouad:** In their defense, the major problem with the regex solutions below if the assumption that `src` will be between double-quotes. – Andrew Moore Jul 28 '09 at 21:00
  • @Andrew Moore I just discovered something that could be a problem for some clients with outdated servers.. Is this class only available for php5+, i mean it does not work with php4? – Ahmad Fouad Jul 28 '09 at 21:25
  • **@Ahmad Fouad:** Should be fairly easy to make it compatible with PHP4. – Andrew Moore Jul 28 '09 at 21:32
  • @Andrew Moore: I think I ripped you off with my answer, which is what I get for skimming. But notice that I used xpath. Do you think that the simplehtmlDOM add-on and the find method are a better way to go? I would probably endorse it more if it was adopted as a documented extension in PHP (or if it used standard syntax. I'm not a find of "find" even if it is more intuitive). – Anthony Jul 28 '09 at 21:34
  • **@Anthony:** `xpath` is great for XML DOM, but when it comes to HTML, I personally like CSS queries better. `SimpleHTMLDom->find()` does just that. It's all a matter of personal preference. – Andrew Moore Jul 28 '09 at 22:08
  • **@Ahmad Fouad:** Here is a slighly older DOM Parser which will work on PHP4 - http://php-html.sourceforge.net/ – Andrew Moore Jul 28 '09 at 22:10
  • **@Anthony:** They are not called *CSS Queries* per-se, but I don't have a better term for it. If you've used jQuery, you should be already famililar with them. `input[type=checkbox]` will return all ``, `ul.some_class li a` will return all `` which has, somewhere in the hierarchy, an `
  • ` parent which has in turn a `
      ` as a parent, but that `
        ` needs to have `class="some_class"`... etc...
  • – Andrew Moore Jul 28 '09 at 22:13
  • Now I remember, the proper term is **SELECTORS**. More examples here: http://docs.jquery.com/Selectors – Andrew Moore Jul 28 '09 at 22:15
  • @andrew: Xpath does the exact same thing, which is part of my resistance to the simplehtmlDOM add-on, because it doesn't use the Xpath syntax. This makes the syntax easier, but less functional and less portable. If you use an xpath query, you can port that query to any other language that does xpath, like js. For your examples: '//input[@type="checkbox"]', '//ul[class="some_class]//li//a"' I do agree that the CSS syntax is better (in jquery at least), but xpath can also do '//tr[td[@class="cost"] > 10]' to get all table rows which have a td of cost and the value is over 10. – Anthony Jul 28 '09 at 22:53
  • **@Anthony:** Until you start doing a selector like `input.some_class.another_class`... (Is it written as `` or ``. In the end, it's all a matter of personal preference. – Andrew Moore Jul 28 '09 at 22:57
  • @Andrew but you do want them to be greedy. if you have `<....img` (where "." is a space), then `<\s*?img` is going to try to match `<`, then `<.`, then `<..`, then `<...`, then finally it will succeed with `<....`. If you just used `<\s*img` it would be much faster – Kip Jul 29 '09 at 11:49
  • please edit the answer to remove the unnecessary `'` from `$image->src';` - Thanks, as I've been looking for this – Ricki May 28 '13 at 17:29