使用preg_replace删除img类

时间:2015-04-30 12:01:20

标签: php preg-replace

我想删除php中的以下

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

我尝试了以下但是它不能正常工作

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

修改 我想删除整行,所以应该没有输出

5 个答案:

答案 0 :(得分:1)

为什么不使用dom和xpath查询在php中尝试dom类,它能够从该img节点中删除该类。不要依赖正则表达式用于dom相关的东西使用php团队提供的Dom类。

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

答案 1 :(得分:1)

yuo可以使用这个简单的正则表达式:

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

即:

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

演示:

http://ideone.com/K1bJUs

答案 2 :(得分:0)

您只需选择课程。这应该适合你:

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

答案 3 :(得分:0)

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

您可以使用php函数替换此类。

答案 4 :(得分:0)

使用preg_replace()从字符串

中删除img标记
<?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;