2015-04-30 34 views
2

刪除IMG類我想刪除下面的PHP 使用的preg_replace

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

我嘗試以下,但它不工作

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

編輯 我要刪除整行所以應該沒有任何輸出

+3

什麼不起作用?你得到了什麼,你期望什麼? – Toto

+0

我想刪除所有內容 – user2650277

+0

你是什麼意思全行? – Saty

回答

0

您只需要選擇班上。這應該爲你做它:

preg_replace('/(?<=\<img)(?class="[\w]+")/', '', $html); 
0
<?php 
echo str_replace("hSprite","",$html); 
?> 

您可以使用PHP函數替換這個類。

0

使用的preg_replace()從字符串

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

檢查編輯.......... – user2650277

+0

@ user2650277編輯我的ans輸出是什麼 – Saty

+1

這將刪除所有' Toto

1

爲什麼你沒試過DOM類在PHP這裏使用DOM和XPath查詢它能夠從IMG節點刪除類刪除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

請仔細閱讀問題,目標是刪除所有標記,而不是將類屬性設置爲空字符串。 –

+0

@CasimiretHippolyte完整的節點是正確的? – gvgvgvijayan

+0

是整個img節點。 –

1

宥可以使用這個簡單的正則表達式:

/<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

+0

這個工作,但在有一個hSprite類的2個圖像的情況下,這個正則表達式捕獲它們之間的所有內容。 –