bateman_ap
bateman_ap

Reputation: 1921

Use Reg Expression to reformat image in RSS feed

I am creating some RSS feeds using PHP (5.2) from a MySQL db specifically for an iPhone app I am making through AppMakr.

They are taken from articles on a website which contain images embedded in them, however in the feeds they don't look great. What I want to try and do is whenever there is an image surround it in <p> so they are on their own line and don't try to wrap around article text.

The format of a image is like this:

 <a rel="lightbox" href="http://images.domain.comk/543/image1.jpg"><img class="imageright" src="http://images.domain.comk/543/image1.jpg" alt="" width="300" height="250" /></a>

So basically surrounded with a <a href> and with a class of "imageright" or "imageleft".

What I would love to change this to is:

 <p><img src="http://images.domain.comk/543/image1.jpg" alt="" width="300" height="250" /></p>

Basically removing the href and imagexxxx class and surrounding in p tags.

I am thinking preg_replace will prob have to be used, but at a loss to what I would actually use for it. Any help is very appreciated.

Upvotes: 1

Views: 187

Answers (2)

Todd Moses
Todd Moses

Reputation: 11029

This Regex matches the opening and closing pair of a specific HTML tag. Anything between the tags is stored into the first capturing group.

'<%TAG%[^>]*>(.*?)</%TAG%>'

This gives us a starting point. Now we need to replace the <a href></a> with <p></p>

PHP provides an easy method to do this in preg_replace()

preg_replace ($pattern, $replacement, $text);

now just insert the correct values:

$patterns = '<%a%[^>]*>(.*?)</%a%>';
$replacement = '<%p%[^>]*>(.*?)</%p%>';
$text = ' <a rel="lightbox" href="http://images.domain.comk/543/image1.jpg"><img class="imageright" src="http://images.domain.comk/543/image1.jpg" alt="" width="300" height="250" /></a>';

echo preg_replace ($pattern, $replacement, $text);

This is a non-tested example and is meant to be used as a pattern. You should read http://www.php.net/manual/en/function.preg-replace.php before creating your solution.

Upvotes: 0

Alexej Kubarev
Alexej Kubarev

Reputation: 853

So you will need to use a regexp for matching like this one:

<a(.*)><img(.*)class="imageright" (.*)></a>

And then a replace regexp like this:

<p><img$2$3></p>

This is not the most flexible one but it should do the trick for preg_replace()

Upvotes: 1

Related Questions