2013-08-27 101 views
0

我想刪除我的domdocument html中的元素標記。操縱PHP domdocument字符串

我有類似

this is the <a href='#'>test link</a> here and <a href='#'>there</a>. 

我想我的HTML改爲

this is the test link here and there. 

我的代碼

$dom = new DomDocument(); 
$dom->loadHTML($html); 
$atags=$dom->getElementsByTagName('a'); 

foreach($atags as $atag){ 
    $value = $atag->nodeValue; 
//I can get the test link and there value but I don't know how to remove the a tag.        
    } 

感謝您的幫助!

+0

您正在尋找名爲['DOMNode :: replaceChild()'](http://php.net/DOMNode.replaceChild)的方法。 – hakre

回答

1

您正在尋找一種名爲DOMNode::replaceChild()的方法。

要使用的,你需要創建$valueDOMDocument::createTextNode())的DOMTextgetElementsByTagName返回自更新列表中,所以當你更換的第一個元素,然後你去到第二,沒有第二再有,只剩下一個元素了。

相反,你需要的第一項一會兒:

$atags = $dom->getElementsByTagName('a'); 
while ($atag = $atags->item(0)) 
{ 
    $node = $dom->createTextNode($atag->nodeValue); 
    $atag->parentNode->replaceChild($node, $atag); 
} 

東西沿着這些線路應該這樣做。

+0

我試過[幾乎一樣](http://3v4l.org/Wddra),但不知道爲什麼只有第一個''標籤會在你工作時被替換。你正在使用的while循環的類型有訣竅!不錯 – hek2mgl

+1

@ hek2mgl:是的,這就是我寫的一個說明:getElementsByTagName的列表自動更新爲具有該標記名的所有當前元素。如果刪除這些元素中的一個元素,列表會更改。 – hakre

0

您可以使用strip_tags - 它應該按照您的要求進行操作。

<?php 

$string = "this is the <a href='#'>test link</a> here and <a href='#'>there</a>."; 

echo strip_tags($string); 

// output: this is the test link here and there.