0

Possible Duplicate:
PHP - remove <img> tag from string

I need to remove an image tag from a string and at the same time replace it with something. Here is what I have:

$body = '<p>Lorem ipsum dolor sit amet:</p>
<p><img class="news" id="" src="images/news_48.png" alt="" /></p>
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p>
<p><img class="gallery" id="26" src="images/gallery_48.png" alt="" /></p>
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>';

I need to do one thing if the image has class="news" and another thing if it's class="gallery". I'm thinking some pseudocode like:

<?php
  if(news){
      replace the image tag where class=news with %%news%%
  }
  if(gallery){
      replace the image tag where class=gallery with %%gallery%%
      assign the value 26 to some variable
  }
?>

So now $body would contain:

$body = '<p>Lorem ipsum dolor sit amet:</p>
<p>%%news%%</p>
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p>
<p>%%gallery%%</p>
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>';

I guess I have to use preg_match/replace, but I'm not good at regex. Any help is appreciated.

Community
  • 1
  • 1
bmla
  • 319
  • 3
  • 10
  • Every time you use a regex on html, a kitten gets stomped on. – Marc B Feb 23 '12 at 02:16
  • @MarkB http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags This is one of (if not) the most popular answers on this website. – annonymously Feb 23 '12 at 02:18
  • Or this: http://stackoverflow.com/questions/1107194/php-remove-img-tag-from-string – krlmlr Feb 23 '12 at 02:25

2 Answers2

0

you can do it like this:

<?php
$body = '<p>Lorem ipsum dolor sit amet:</p>
<p><img class="news" id="" src="images/news_48.png" alt="" /></p>
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p>
<p><img class="gallery" id="26" src="images/gallery_48.png" alt="" /></p>
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>';

if (preg_match('{.*<img class="gallery".*}', $body)) {
    $some_variable = 26;
}

print preg_replace('{<img class="(news|gallery)".*/>}', '%%\\1%%', $body);

?>
dennisyuan
  • 171
  • 1
  • 10
0

Thanks, I ended up with this. It kind of works :)

<?php
    $str = preg_replace('/<img class="news"[^>]+\>/i', "%%news%%", $str);
    preg_match('/<img class="gallery" id="(.*?)"[^>]+\>/i', $str, $id);
    $id = $id[1];
    $str = preg_replace('/<img class="gallery"[^>]+\>/i', "%%gallery%%", $str);
    echo $str;
?>

But then I thought about, what if I have two or more gallery images and want to fetch their ids' too. A %%gallery%% would have to be linked to it's respective id, for each %%gallery%%, in some way.

bmla
  • 319
  • 3
  • 10