views:

39

answers:

3

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"&gt;&lt;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.

A: 

Would something like this work for you?


<?php
$img_html = '<a rel="lightbox" href="http://images.domain.comk/543/image1.jpg"&gt;&lt;img class="imageright" src="http://images.domain.comk/543/image1.jpg" alt="" width="300" height="250" /></a>';
preg_match(
  '/.*(<img.*\/>).*/', 
  $img_html, 
  $matches
);
echo sprintf("<p>%s</p>", $matches[1]);

jtp
+1  A: 

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()

AlexejK
Many thanks all, with a combination of help I managed to work out the RegEx needed, I ended up using: `$imagePattern = '/<a.*><img.*src="(.*)" alt.*>/';$imageReplacement = '<p><img src="$1"></p>';$intro = preg_replace($imagePattern, $imageReplacement, $intro);`
bateman_ap
A: 

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"&gt;&lt;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.

Todd Moses