2009-09-08 72 views
2

是否有人知道修改過的strip_tags函數是否存在,您可以指定要剝離的標記的ID,並且possbile還可以指定刪除標記中的所有數據。舉個例子:帶有特定ID的div的PHP Strip_tags?

<div id="one"> 
    <div id="two"> 
    bla bla bla 
    </div> 
</div> 

Running: 


new_strip_tags($data, 'two', true); 

必須返回:

<div id="one"> 
</div> 

有沒有這樣的事了嗎?

回答

1

這並不完全是strip_tags所做的,它會去掉標籤但留下內容。你想要的是這樣的:

function remove_div_with_id($html, $id) { 
    return preg_replace('/<div[^>]+id="'.preg_quote($id, '/').'"[^>]*>(.*?)<\/div>/s', '', $html); 
} 

請注意,這將無法正確使用嵌套標籤。如果你需要,你可能想使用HTML的DOM表示。

+0

代碼無法正常工作 – 2013-05-22 13:56:12

8

您可以使用DOMDocumentDOMXPath

<?php 
$html = '<html><head><title>...</title></head><body> 
    <div id="one"> 
    <div id="two"> 
     bla bla bla 
    </div> 
    </div> 
</body></html>'; 

$doc = new DOMDocument; 
$doc->preserveWhiteSpace = false; 
$doc->loadhtml($html); 

$xpath = new DOMXPath($doc); 

$ns = $xpath->query('//div[@id="two"]'); 
// there can be only one... but anyway 
foreach($ns as $node) { 
    $node->parentNode->removeChild($node); 
} 
echo $doc->savehtml();