Regular expression to get img attributes

Here’s what i want to do:

  • Search a piece of HTML for any images (img tags)
  • Retrieve the width, height and src for all the images.

Using preg_match_all(), I have managed to get the following regular expression to work:

'!<\\s*img\\s{1}.*width=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*height=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*src=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*>!ixU'

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.

a reg exp that will retrieve the attributes regardless of the order would be much appreciated.

It’s probably easier to just look for the individual attributes.

'!<\\s*img\\s{1}.*(width|height|src)=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*(width|height|src)=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*(width|height|src)=[\\'"]{1}([^\\'"]*)[\\'"]{1}.*>!ixU'

this is the closest I’ve come up with for what your asking

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>';