Preg_replace

Ok I need to wrap images in a div. I have a chunk of content which will contain text, images, links etc. I need to go through it and take every image found and wrap it in a div. What makes it even more difficult is that some of the images will be links, in which case the link with the image will need to be wrapped in a div.

Question is, when you use 'or' in a regex replace, is there any way to do it all with one preg_replace() ? In the following code, only the first match will be replaced, in the event it is wrapped by <a>, it becomes $2. Am I missing something? Or do I have to do this in 2 separate preg_replace calls?

I would generally advise against using your own regexps for parsing HTML. There are loads of proper HTML parsers out there that will make life much easier in the long run once you've figured out how to use them.