Match All Image Tags Using REGEX
While I am busy with the update of The Attached Image (which is taking a while) I thought I’d write a post about something that is commonly searched for, or so I’ve read. Matching image tags using REGEX can be difficult, but I’m here to, hopefully, make it easier.
To match all image tags in a string that contain a source attribute (which is the most sensible thing to do) you use the following PHP code:
1 |
preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/", $string, $matches, PREG_PATTERN_ORDER); |
Where $string
is the variable containing the content to match on, $matches
is an array created to contain all the matches and PREG_PATTERN_ORDER
determines the order in which the matches are placed into the $matches
variable. You can find other flags at php.net.
The matches array will now contain entries. The first (Key 0) will contain an array of matches provided by the entire REGEX pattern, where as the second (Key 1) will contain an array of matches provided by the first sub pattern (which is contained in parentheses) and so on.
This is the REGEX pattern used in the in post functionallity of The Attached Image & I use the second key as it holds the contents of the sub pattern which is the images path.
Anyway there you have it, a quick bit of REGEX that will hopefully help anyone wanting to find all the images in a string of HTML. If you are wondering how to get the content then it could either be a string, or you could use output buffering, but that is for another time. 🙂