Match All Image Tags Using REGEX

/ PHP / by Paul Robinson / 0 comments
This post was published back on October 31, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more