user2650277
user2650277

Reputation: 6739

Remove img class using preg_replace

I want to remove the following line in php

<img class="hSprite" src="something" width="160" height="120"
sprite="/t/3010187.jpg" id="3010187">

I tried the following but its not working

preg_replace("@<img class=\"hSprite\".*?>@s", "", $html);

EDIT I want to delete the whole line so there should be nothing output

Upvotes: 2

Views: 1223

Answers (5)

Pedro Lobito
Pedro Lobito

Reputation: 98921

yuo can use this simple regex:

/<img.*?class="hSprite".*?>/

i.e.:

<?php

$html = <<< LOL
 <div class="refsect1 description" id="refsect1-reserved.variables.server-description">
  <h3 class="title">Description</h3>
  <p class="para">
   <var class="varname"><var class="varname">test</var></var> is an array containing information
   such as headers, paths, and script locations. The entries in this
   array are created by the web server. There is no guarantee that
   every web server will provide any of these; servers may omit some,
   or provide others not listed here. That said, a large number of
   these variables are accounted for in the <a href="http://www.faqs.org/rfcs/rfc3875" class="link external">test 9999</a>, so you should
   be able to expect those.
  </p>
<img class="hSprite" src="something" width="160" height="120"
sprite="/t/3010187.jpg" id="3010187">
LOL;

$newHtml = preg_replace('/<img.*?class="hSprite".*?>/sim', '', $html);

echo  $newHtml;

Demo:

http://ideone.com/K1bJUs

Upvotes: 1

gvgvgvijayan
gvgvgvijayan

Reputation: 2506

Why not you tried dom class in php here using dom and xpath query it is able to remove the class from that img node. Don't depend on regex for dom related things use Dom classes provided by php team.

$text = 
<<<heredoc
        <img class="hSprite" src="something" width="160" height="120"
sprite="/t/3010187.jpg" id="3010187">
heredoc;

$doc = new DOMDocument();
$doc->loadHTML($text);

//$img = $doc->getElementsByTagName("img")->item(0);

$xpath = new DOMXPath($doc);

$expression = "//*[contains(@class, 'hSprite')]";
$classElements = $xpath->query($expression);

foreach ($classElements as $element) {
    //$element->attributes->getNamedItem("class")->nodeValue = '';
    $element->parentNode->removeChild($element);
}

//echo $doc->saveHTML($img);
echo $doc->saveHTML();

Upvotes: 1

Saty
Saty

Reputation: 22532

Use preg_replace() to remove img tag from string

<?php

$html='nothing<img class="hSprite" src="something" width="160" height="120"
sprite="/t/3010187.jpg" id="3010187">';

$content = preg_replace("/<img[^>]+\>/i", "", $html); 
echo $content;

Upvotes: 0

Muhammad Ahmed
Muhammad Ahmed

Reputation: 481

<?php
echo str_replace("hSprite","",$html);
?>

You can use php function for replace this class.

Upvotes: 0

Styphon
Styphon

Reputation: 10447

You need to only select the class. This should do it for you:

preg_replace('/(?<=\<img)( ?class="[\w]+")/', '', $html);

Upvotes: 0

Related Questions