1

I need to remove all images in a variable using the following pattern. (With PHP).

<div class="float-right image"> 
  <img class="right" src="http://www.domain.com/media/images/image001.png" alt="">
</div>

All the div tags will have an image class, but the float-right might vary. I can't seem to get the regex working, please help me.

Lukas Oppermann
  • 2,918
  • 6
  • 47
  • 62

2 Answers2

3

Use a DOM instead of regex. Example:

<?php
$doc = new DOMDocument();
$doc->loadHTML('<div class="float-right image"> 
  <img class="right" src="http://www.domain.com/media/images/image001.png" alt="">
</div>');

foreach( $doc->getElementsByTagName("div") as $old_img ) {
    $img = $doc->createElement("img");
    $src = $doc->createAttribute('src');
    $class = $doc->createAttribute('class');
    $src->value = 'http://your.new.link';
    $class->value = 'right';
    $img->appendChild($src);
    $img->appendChild($class);
    $doc->replaceChild($img, $old_img);
}

echo $doc->saveHTML();
?>
dimme
  • 4,393
  • 4
  • 31
  • 51
  • Hey, I did try it, but it seems to not work on the server somehow. But basically, all I need is to find a div with the class "image" and possible other classes, but they do not matter. Than I just want to remove the whole div from the string. How can I do this with regex? – Lukas Oppermann Nov 12 '11 at 15:46
  • I don't know regex even though I tried many times to learn it, so I'm trying to avoid it. – dimme Nov 12 '11 at 22:21
1

This regex matches your pattern:

(?s)<div class="[^"]*">\W*<img\W*class="[^"]*"\W*src="[^"]*"\W*alt="[^"]*">\W*</div>

I have tested it against several strings. It will work on:

<div class="anything"> 
<img class="blah" src="anything" alt="blah">
</div>

, where you can replace the "blah" and "anything" strings with anything. Also, the various \W* in the regex allow for different spacing from string to string.

You said you want to do this in PHP.

This will zap all the matched patterns from a page stored in the $my_html variable.

$my_html=preg_replace('%(?s)<div class="[^"]*">\W*<img\W*class="[^"]*"\W*src="[^"]*"\W*alt="[^"]*">\W*</div>%m', '', $my_html);

I think this is what you were looking for?

zx81
  • 41,100
  • 9
  • 89
  • 105