View Full Version : Help to simplify regex mess

05-08-2009, 05:30 AM
Can someone please help me to clean this up. This works, but there has to be a nicer way to do it. The goal is to create popup links to images uploaded through out CMS, except for ones that have class="nopopup" applied to them. So, the first line puts things together to look like imgclass="nopopup". The second line changes img tags with this to <noimg so that next line which creates the popups won't do anything to these img tags. The final line converts the <noimg back to <img so that the image will actually be displayed.

Would really appreciate some help simplifying this.

$content = preg_replace('/<img(.*?)(class="nopopup")(.*?)>/i', '<img$2$1$3>', $content);
$content = str_replace('<imgclass="nopopup"','<noimg',$content);
$content = preg_replace('/<img(.*?)src="(.*?)\.(.*?)"(.*?)>/i', '<a href="$2_lge.$3" class="highslide" onclick="return hs.expand(this)" onmouseover="Tip(\'Click to Enlarge\', WIDTH, 0)" onmouseout="UnTip()"><img src="$2.$3" $1 $4></a>', $content);
$content = str_replace('<noimg','<img',$content);

05-08-2009, 06:52 AM
I'm not the best at regular expression but this is my try at it and I'm sure there's a way to do it in only one regular expression.

$string = <<<HTML
<img src="popup.jpg" alt="" />
<img src="nopopup.jpg" class="nopopup" alt="" />

echo preg_replace('#<img.*src="([^"]+)"[^>]*(?<=class="nopopup").*>#i', '$1', $string);

The only problem with this is that the class has to be AFTER the source, nothing more. I haven't added the replacement, I'll leave that up to you.

05-08-2009, 07:14 AM
Hi Iszak,

Thanks very much for the quick response.

That is the approach I was initially trying to take, but the problem is that the recent versions of tinymce (which I am using as the text editor in my CMS) reorder tag attributes and the title and class attributes are always seem to be located immediately after the <img. I guess I could rewrite what you put together to handle the class being before the src, but I was hoping for something more robust that would handle any order. I am thinking that there must be a way to make the match, conditional on there being no class="nopopup" anywhere between the <img and the /> but I can't seem to figure it out.

As horrible as my approach is, it does seem to handle having the img attributes in any order.

Any ideas how that might be possible with one preg_replace?


EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum