操作PHP domdocument字符串


manipulate PHP domdocument string

我想删除我的domdocument html中的元素标记。

我有类似的东西

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.                              
     }

谢谢你的帮助!

您正在寻找一个名为DOMNode::replaceChild()的方法。

为了利用这一点,您需要创建$valueDOMDocument::createTextNode())的DOMText,并且getElementsByTagName还返回一个自更新列表,因此当您替换第一个元素,然后转到第二个元素时,不再有第二个,只剩下一个a元素。

相反,你需要在第一项上花一段时间:

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

应该有这样的方法。

您可以使用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.