Lukas Oppermann
Lukas Oppermann

Reputation: 2938

PHP Regex: remove div with class "image"

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.

Upvotes: 1

Views: 2087

Answers (2)

zx81
zx81

Reputation: 41838

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?

Upvotes: 1

dimme
dimme

Reputation: 4424

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

Upvotes: 3

Related Questions