问题描述
给出以下HTML:
$content = '<html>
<body>
<div>
<p>During the interim there shall be nourishment supplied</p>
</div>
</body>
</html>';
如何将其更改为以下HTML:
How can I alter it to the following HTML:
<html>
<body>
<div>
<p>During the <span>interim</span> there shall be nourishment supplied</p>
</div>
</body>
</html>
我需要使用DomDocument进行此操作.这是我尝试过的:
I need to do this using DomDocument. Here's what I've tried:
$dom = new DomDocument();
$dom->loadHTML($content);
$dom->preserveWhiteSpace = false;
$xpath = new DOMXpath($dom);
$elements = $xpath->query("//*[contains(text(),'interim')]");
if (!is_null($elements)) {
foreach ($elements as $element) {
$text = $element->nodeValue;
$element->nodeValue = str_replace('interim','<span>interim</span>',$text);
}
}
echo $dom->saveHTML();
但是,这将输出文字html实体,因此它将在浏览器中呈现为:
However, this outputs literal html entities so it renders like this in the browser:
During the <span>interim</span> there shall be nourishment supplied
我想人们应该使用 createElement
和 appendChild
方法,而不是直接分配 nodeValue
,但是我看不到如何在其中插入元素textNode字符串的中间?
I imagine one should use createElement
and appendChild
methods instead of assigning nodeValue
directly but I can't see how to insert an element in the middle of a textNode string?
推荐答案
Marcus Harrison使用 splitText
的答案是一个很好的答案,但是它可以简化,并且需要使用mb_ *方法来使用UTF.-8输入:
Marcus Harrison's answer using splitText
is a good one, but it can be simplified and needs to use mb_* methods to work with UTF-8 input:
<?php
$html = <<<END
<html>
<meta charset="utf-8">
<body>
<div>
<p>During € the interim there shall be nourishment supplied</p>
</div>
</body>
</html>
END;
$replace = 'interim';
$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query(sprintf('//text()[contains(., "%s")]', $replace));
foreach ($nodes as $node) {
$start = mb_strpos($node->textContent, $replace);
$end = $start + mb_strlen($replace);
$node->splitText($end); // do this first
$node->splitText($start); // do this last
$newnode = $doc->createElement('span');
$node->parentNode->insertBefore($newnode, $node->nextSibling);
$newnode->appendChild($newnode->nextSibling);
}
$doc->encoding = 'UTF-8';
print $doc->saveHTML($doc->documentElement);
这篇关于如何在文本节点的文本中间添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!