PHP
Extract Image Tags and SRC Attributes from HTML
A PHP regex pattern to efficiently find all `<img>` tags and extract their `src` attribute values from an HTML string for content analysis.
<?php
function extractImageSources(string $htmlContent): array {
$matches = [];
// Regex to find <img> tags and capture the src attribute
$img_src_regex = '/<img[^>]*src="([^"]*)"[^>]*>/i';
preg_match_all($img_src_regex, $htmlContent, $matches);
return $matches[1] ?? [];
}
// Example Usage:
$html = '<p>Some text</p><img src="image1.jpg" alt="Description 1"><p>More text</p><img src="/path/to/image2.png">';
$imageSources = extractImageSources($html);
print_r($imageSources);
// Expected: ['image1.jpg', '/path/to/image2.png']
?>
How it works: This PHP function uses a regular expression to parse an HTML string, specifically looking for `<img>` tags. It then extracts and returns an array of all `src` attribute values found within these image tags. This is useful for processing user-generated HTML, content analysis, or dynamically building image galleries without needing a full DOM parser.