2013-03-26 75 views
1

我解析HTML中的PHP和我無法控制的原始內容我想剝奪它的樣式和不必要的標籤,同時仍然保持內容和標籤的短名單,分別是:我怎樣才能刪除所有的標記,除了從PHP解析的HTML允許列表中刪除PHP

p,IMG,IFRAME(也許其他幾個)

我知道我可以刪除特定標籤(見代碼我使用這下面)但是因爲我不一定知道它們可能是什麼標籤,而且我也不想創建大量可能的列表,我希望能夠剝離除我允許的列表之外的所有內容。

function DOMRemove(DOMNode $from) { 
    $sibling = $from->firstChild; 

    do { 
     $next = $sibling->nextSibling; 
     $from->parentNode->insertBefore($sibling, $from); 
    } while ($sibling = $next); 

    $from->parentNode->removeChild($from); 
} 

$dom = new DOMDocument; 
$dom->loadHTML($html); 

$nodes = $dom->getElementsByTagName('span'); 
+3

奇怪的是,有一個名爲strip_tags的函數已經內置到PHP中。 http://www.php.net/manual/en/function.strip-tags.php – 2013-03-26 02:21:31

+0

哦,親愛的:(一個經典的隧道視覺案例,我應該先考慮過這個方法。 – Finglish 2013-03-26 08:07:30

回答

5

所講的上述cpattersonv1,你可以簡單地使用strip_tags()作業。

<?php 

// strip all other tags except mentioned (p, img, iframe) 
$html_result = strip_tags($html, '<p><img><iframe>'); 

?> 
相關問題