PHP DOM 删除标签(不是内容)


PHP DOM removing the tag (not content)

$mystring="This is mystring. <a href='http://www.google.com'>Google.</a>"; 
$dom = new DOMDocument; 
$dom->loadHTML($mystring); 
$xPath = new DOMXPath($dom); 
$nodes = $xPath->query('//a');
if($nodes->item(0)) { 
    $nodes->item(0)->parentNode->removeChild($nodes->item(0)); 
} 
echo $dom->saveHTML();  

我想得到输出:

这是我的字符串。谷歌。

但我得到的只是:

这是我的字符串。

尝试以下操作:

if($nodes->item(0)) {
    $node = $nodes->item(0);
    $node->parentNode->replaceChild(new DOMText($node->textContent), $node); 
} 
或者

,使用简单的技术来做简单的事情。

这是 strip_tags(( 的替代方法

preg_replace('#<a.*?>(.*?)</a>#i', ''1', $text)
">

Google"是您尝试删除的节点的子节点。因此,此行为是意料之中的。我认为你想要的是使用PHP的strip_tags函数。

echo strip_tags("This is mystring. <a href='http://www.google.com'>Google.</a>");
相关文章: