如何在文本节点的文本中间添加元素?

编程入门 行业动态 更新时间:2024-10-20 03:55:28
本文介绍了如何在文本节点的文本中间添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出以下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);

更多推荐

如何在文本节点的文本中间添加元素?

本文发布于:2023-06-07 21:59:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   节点   元素   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!