VORiAND
VORiAND

Reputation: 175

Replace IMG tag

I'm not that good with this REGEX string replace, but i think this problem can be solved with that...

I want to replace this:

<a href="http://www.example.com">
<img alt="" class="aligncenter size-full wp-image-112" height="300" src="http://www.example.comsample1.png" title="sample1" width="300" /></a>

with this:

<p style="text-align:center;"><a href="http://www.example.com">
<img alt="" class="aligncenter size-full wp-image-112" height="300" src="http://www.example.comsample1.png" title="sample1" width="300" /></a></p>

and this (if no link given):

<img alt="" class="aligncenter size-full wp-image-112" height="300" src="http://www.example.comsample1.png" title="sample1" width="300" />

with this:

<p style="text-align:center;">
<img alt="" class="aligncenter size-full wp-image-112" height="300" src="http://www.example.comsample1.png" title="sample1" width="300" /></p>

How can i make this work? (the search keyword is the 'class="aligncenter ', if this exist in the IMG tag, then i need to replace)

There could be many IMG or tags to replace, not only one!

Thank you very much!!!

Upvotes: 0

Views: 518

Answers (1)

Vyktor
Vyktor

Reputation: 21007

You'll probably need two regexps, one for img (making sure that there's no <a before or after <img /> tag, that what's look ahead, you'll need negative look ahead assertion so it will look like this:

$text = preg_replace( '~<img alt="" class="aligncenter size-full wp-image-112"([^<>]+)/>\s*(?!</a)~mi', '<p style="text-align:center;">\0</p>', $text);

m will match new lines in \s* and i makes regexp case insensitive, \0 reffers to whole matched text

Replace for <a ...><img /> will be similar:

$text = preg_replace( '~<a href="([^"]+)"><img alt="" class="aligncenter size-full wp-image-112"([^<>]+)/>\s*</a>~mi', '<p style="text-align:center;">\0</p>', $text);

Upvotes: 3

Related Questions