1

I have this code that extracts the first image from an article in joomla:

<?php preg_match('/<img (.*?)>/', $this->article->text, $match); ?>
<?php echo $match[0]; ?>

Is there a way to extract all the images that are available in the article and not only one?

NikiC
  • 100,734
  • 37
  • 191
  • 225
themhz
  • 8,335
  • 21
  • 84
  • 109

2 Answers2

2

I may suggest first to not use Regular Expressions to parse HTML. You should use an appropiate parser such as DOMDocument::loadHTML which uses libxml.

Then you may query for the desired tags you want. Something like this may work (untested):

$doc = new DOMDocument; 
$doc->loadHTML($htmlSource);

$xpath = new DOMXPath($doc);
$query = '//img';
$entries = $xpath->query($query);
foreach ($entries as $entry) {
  // $entry->getAttribute('src')
}
Community
  • 1
  • 1
Alexander
  • 23,432
  • 11
  • 63
  • 73
  • I like this approach since I have access to the attributes and i let xpath do the job. You also answered first so you win. Thanx – themhz Feb 17 '12 at 04:30
  • just to mention that I used it again. To bad I can't also like again :P – themhz Aug 27 '13 at 21:26
1

Use preg_match_all. And you'll want to modify the pattern like so to take into account the trailing '/' inside the img tag.

$str = '<img src="asdf" />stuff more stuff <img src="qwerty" />';
preg_match_all('/<img (.*?)\/>/', $str, $matches);
print_r($matches);

Array
(
    [0] => Array
        (
            [0] => <img src="asdf" />
            [1] => <img src="qwerty" />
        )

    [1] => Array
        (
            [0] => src="asdf" 
            [1] => src="qwerty" 
        )

)
David Xia
  • 5,075
  • 7
  • 35
  • 52