从DOM对象中删除一个跨度,但不删除其内容,并将其保存到变量中 [英] Removing a span from a DOM object but not the content and save it to a variable
本文介绍了从DOM对象中删除一个跨度,但不删除其内容,并将其保存到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下字符串:
<span>This <b>is</b> an <span class="something">example</span></span>
我要删除跨度,但不删除内容.
And I want to remove the spans but not the content.
$content = '<span>This <b>is</b> an <span class="something">example</span></span>';
$dom = new DOMDocument();
$dom->loadXML($content);
$nodes = $dom->getElementsByTagName('span');
foreach ($nodes as $node) {
// remove span but not content
}
$dom->save($var); // $dom->save() saves to file but I want to save to $var
$var
包含:This <b>is</b> an example
.
所以基本上我有两个问题:
So basically I have two questions:
- 如何删除
span
s - 如何将剥离的字符串保存到变量
- How to remove the
span
s - How to save the stripped string to a variable
推荐答案
这种方法应该可以解决问题:
Something like this should do the trick:
<?php
function removeTag($content, $tagName) {
$dom = new DOMDocument();
$dom->loadXML($content);
$nodes = $dom->getElementsByTagName($tagName);
while ($node = $nodes->item(0)) {
$replacement = $dom->createDocumentFragment();
while ($inner = $node->childNodes->item(0)) {
$replacement->appendChild($inner);
}
$node->parentNode->replaceChild($replacement, $node);
}
return $dom->saveHTML();
}
$content = '<span>This <b>is</b> an <span>example</span></span>';
echo removeTag($content, 'span'); // echos "This <b>is</b> an example"
这篇关于从DOM对象中删除一个跨度,但不删除其内容,并将其保存到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文