-1

I am building a small cms system for personal use. A part of it requires me to get the first image url in an article. How can I do this?

Sample article content in variable $article

<p>
<img src="/images/userContent/2013-07-12%2022_27_34.png">
The griefing problem has been curbed!
</p>

How can I get the url /images/userContent/2013-07-12%2022_27_34.png
Possibly regex? if yes, how? I am clueless with regex

Krimson
  • 7,386
  • 11
  • 60
  • 97
  • possible duplicate of this http://stackoverflow.com/questions/7461922/just-get-the-image-url-from-string-in-php – Srikanth AD Aug 15 '13 at 21:24
  • 2
    Using regular expressions to parse (X)HTML will cause an encounter with [Cthulhu](http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html). – Mike Aug 15 '13 at 21:29
  • correctly answered [here](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Javier Aug 15 '13 at 21:38
  • @Javier If the OP visited Mike's link, he probably would've found that answer. – BLaZuRE Aug 15 '13 at 21:42

1 Answers1

3

Use the DOMDocument class:

<?php
    $myhtml = '...'
    $doc = new DOMDocument();
    $doc->loadHTML($myhtml);
    $imageTags = $doc->getElementsByTagName('img');

    foreach($imageTags as $tag) {
        echo $tag->getAttribute('src');
    }
?>

Output:

/images/userContent/2013-07-12%2022_27_34.png

Working demo!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150