2010-08-11 62 views
0

這是一個簡單的:)問題用了preg_replace

我有這行的偉大工程:

$listing['biz_description'] = preg_replace('/<!--.*?--\>/','',$listing['biz_description']); 

什麼是正確的正則表達式來刪除HTML實體版本?

這是實體:

&lt;!-- --&gt; 

回答

0

我只想解碼HTML實體如果你很高興與preg_replace函數的正則表達式你已經有 ... html_entity_decode作爲@ircmaxell提到的,使用正則表達式的HTML解析可以是非常痛苦的。

$str = "This is a <!-- test --> of the emergency &lt;!-- broadcast --&gt; system"; 
$str = preg_replace('/<!--.*?--\>', '' ,html_entity_decode($str)); 
echo $str; 
+0

咄,我應該想到這一點早笑。所有的正則表達式都在解析描述字段,所以它對服務器不是很重要。 謝謝! – Joe 2010-08-11 20:55:47

0

NEVER use regex to parse HTML/XML ...

用的DomDocument的實現(假設有效的XML):

$dom = new DomDocument(); 
$dom->loadXml($listing['biz_description']); 
removeComments($dom); 
$listing['biz_description'] = $dom->saveXml(); 

function removeComments(DomNode $node) { 
    if ($node instanceof DomComment) { 
     $node->parentNode->removeChild($node); 
    } else { 
     foreach ($node->childNodes as $child) { 
      removeComments($child); 
     } 
    } 
}