View Full Version : Regular Expressions

01-16-2008, 03:18 PM

I'm not a regex man, so I need some help to make a search & replace!
I get from a table an article body and I want to find any anchor that as an image tag and apply a specific css class to the anchor;

Reading some tutorials I already reach something that I think it works, but I need to replace the string.

$a = '<a href="image/test.gif"><img src="image/test.gif" /></a>';

if (preg_match("/^(<a href.*?<img src.*?<\/a>)$/", $a, $matches)) {
echo "Match was found <br />";
echo htmlspecialchars($matches[0])."<br>";


I need to find '<a href' AND '<img src' AND '</a>' ... if it finds this pattern then should replace '<a href' with '<a href class="abcd"'.



Edited: I forgot to mention that the image must be the same in the anchor and in the image tag!

01-16-2008, 03:51 PM
Try this:

$text = '<a href="image/test.gif"><img src="image/test.gif" /></a>';

$text = preg_replace( '#<a(.*?)>(.*?<img.*?)</a>#is', '<a$1 class="abcd">$2</a>', $text );

echo $text;


<a href="image/test.gif" class="abcd"><img src="image/test.gif" /></a>

01-16-2008, 03:58 PM
That works ...

It is possible to match the image file 'path/name'.
It needs to be the same in the anchor and in the img tag.

This class only applies to images!

Thanks, N

01-16-2008, 04:10 PM
Ok, try this instead:

$text = preg_replace( '#<a(.*?href="(.*?)".*?)>(.*?<img.*?src="\2".*?)</a>#is', '<a$1 class="abcd">$3</a>', $text );

01-16-2008, 04:17 PM
$a = '<a href="image/test.gif"><img src="image/test.gif" /></a>';
$text = preg_replace(
'/<a href="([^"]+)">\w*<img src="\1" ?\/>\w*<\/a>/',
'<a href="$1"><img class="abcd" src="$1"/></a>',
echo $text

01-16-2008, 04:25 PM

Every sample works very well, but none match the image path and name!

<a href="image/test.gif"><img src="image/test.gif" /></a>

Bold anchor and src must be the same!

01-16-2008, 07:09 PM
In both our examples they do have to be exactly the same, try changing the src or href and the regex won't match.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum