PHP DOMElement将文本节点中的字符串替换为元素



我有一个如下形式的DOMElement:

<text>This is some text with <i>some words in italics and <b>bold</b></i>.</text>

我想在这个元素的所有文本节点中,将某个字符串(比如"some"(包装在另一个元素(比如<span></span>(中。所以结果应该是:

<text>This is <span>some</span> text with <i><span>some</span> words in italics and <b>bold</b></i>.</text>

如何做到这一点?应该假设文本节点可以处于任意深度。

提前感谢您的帮助!

这需要一点破解,但有了下面的内容(根据您的实际html进行调整,而不是下面假设的内容(,您应该会达到目的。

$str = <<<XXX
<doc>
<div><text>This is some text with <i>some words in italics and <b>bold</b></i>.
</text>
</div>
</doc>
XXX;

$xml = new DOMDocument();
$xml->loadXML($str);
$xpath = new DOMXpath($xml);
#locate the existing DOMElement
$originalNode = $xpath->query('//text')[0];
#extract its innerHTML
$original_ih =  $originalNode->ownerDocument->saveHTML($originalNode);
#now the hack...
$temp = str_replace('words','xxxwordsxxx', $original_ih);
$sa = explode('xxx',$temp);
$final_ih = "{$sa[0]}<span>{$sa[1]}</span>{$sa[2]}";
#import the new innerHTML into the DOM:
$fragment = $xml->createDocumentFragment();
$fragment->appendXML($final_ih);
#replace the old with the new
$originalNode->parentNode->replaceChild($fragment, $originalNode);
echo $xml->saveHTML();

输出:

<doc>
<div><text>This is some text with <i>some <span>words</span> in italics and <b>bold</b></i>.
</text>
</div>
</doc>

编辑:从修改后的元素创建新文档:

$xml_new = new DOMDocument();
$xml_new->loadXML($final_ih);
echo $xml_new->saveHTML();

输出:

<text>This is some text with <i>some <span>words</span> in italics and <b>bold</b></i></text>

最新更新