My stackoverflow answer #10

by krike in Other / Stackoverflow answers on 08 Dec 2010


Each week I feature one of my answers on stackoverflow hoping it might help other people.

The question

This weeks question by T1000: Regular expression match all image URLs

I need help to make preg_match_all() for every image URL on random page.
As far I do this

preg_match_all('/img[dD]+?src=('|")([dD]+?)('|")/i', $page, $matches); 

But won’t work for every page. Must match all possible image closed in img src also ones that doesn’t look like images. thank you

My anwser

use the html DOM parser -> http://simplehtmldom.sourceforge.net/

all you need to do then is use this code:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.