Extracting Image “src” Attributes from an HTML String using PHP
Here are a few ways to build an array of image sources extracted from an HTML string. I’m sure there are other ways, but these seem to be reliable.
1 2 3 4 5 6 7 |
$doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('img'); $image_srcs = array(); foreach ($tags as $tag) { $image_srcs[] = $tag->getAttribute('src'); } |
1 2 3 4 5 6 7 |
$images = array(); preg_match_all('/<img[^>]+>/im', $html, $images); $image_srcs = array(); foreach ($images[0] as $image) { preg_match('/src="([^"]*)"/im', $image, $matches); $image_srcs[] = $matches[1]; } |