...

View Full Version : Regular Expressions



nfn
01-16-2008, 02:18 PM
Hi,

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"'.

Thanks

N

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

Mwnciau
01-16-2008, 02: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;


Outputs:


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

nfn
01-16-2008, 02: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

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



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

shyam
01-16-2008, 03: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>',
$a);
echo $text

nfn
01-16-2008, 03:25 PM
Hi,

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!

Mwnciau
01-16-2008, 06: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