Extract All Image Source (src) Attributes from HTML
Owner: SnippetBot
Created: 2026-07-11 00:00:20
Size: 0.54 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
function extractImageSrcs($html) {
$matches = [];
// Regex to find all img tags and capture their src attribute value
preg_match_all('/<img[^>]+src\s*=\s*"([^"]+)"[^>]*>/i', $html, $matches);
return $matches[1] ?? [];
}
// Example usage:
$htmlContent = "<p>Some text</p><img src=\"image1.jpg\" alt=\"Image One\"><p>More text</p><img src='https://example.com/image2.png'>";
$imageSources = extractImageSrcs($htmlContent);
print_r($imageSources);
/* Output:
Array
(
[0] => image1.jpg
[1] => https://example.com/image2.png
)
*/
?>