【发布时间】:2014-12-27 22:13:39
【问题描述】:
我正在尝试使用 DOMDocument,但遇到了一些问题。我有一个这样的字符串:
Some Content to keep
<span class="ice-cts-1 ice-del" data-changedata="" data-cid="5" data-time="1414514760583" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
This content should remain, but span around it should be stripped
</span>
Keep this content too
<span>
<span class="ice-cts-1 ice-ins" data-changedata="" data-cid="2" data-time="1414512278297" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
This whole node should be deleted
</span>
</span>
我想要做的是,如果跨度有像ice-del 这样的类,则保留内部内容但删除跨度标签。如果它有ice-ins,则删除整个节点。
如果它只是一个空范围 <span></span> 也将其删除。这是我的代码:
//this get the above mentioned string
$getVal = $array['body'][0][$a];
$dom = new DOMDocument;
$dom->loadHTML($getVal );
$xPath = new DOMXPath($dom);
$delNodes = $xPath->query('//span[@class="ice-cts-1 ice-del"]');
$insNodes = $xPath->query('//span[@class="ice-cts-1 ice-ins"]');
foreach($insNodes as $span){
//reject these changes, so remove whole node
$span->parentNode->removeChild($span);
}
foreach($delNodes as $span){
//accept these changes, so just strip out the tags but keep the content
}
$newString = $dom->saveHTML();
所以,我的代码可以删除整个跨度节点,但我如何获取一个节点并去掉它的标签但保留它的内容?
另外,我将如何删除并清空跨度?我确定我可以使用正则表达式或替换来做到这一点,但我有点想使用 dom 来做到这一点。
谢谢
【问题讨论】:
标签: php html xpath domdocument