Since I can not rely on that width, height and src will always appear in that order, a reg exp that will retrieve the attributes regardless of the order would be much appreciated.
whytewolf’s example works great for what you’re doing…but if you want to grab all the attributes for each image tag, I don’t know if it can be done using only 1 regex and without using lots of pipes (i.e. (width|height|src|alt|src|etc…).
This will grab all the attributes for each image:
// grab all image tags
preg_match_all("#<img(.*?)\\/?>#", $html, $matches);
// extract attributes from each image and place in $images array
$images = array();
foreach ($matches[1] as $m) {
preg_match_all("#(\\w+)=['\\"]{1}([^'\\"]*)#", $m, $matches2);
// code below could be a lot neater using array_combine(), but it's php5 only
$tempArray = array();
foreach($matches2[1] as $key => $val) {
$tempArray[$val] = $matches2[2][$key];
}
$images[] = $tempArray;
}
// show results
echo '<pre>';
print_r($images);
echo '</pre>';