douyun8885 2016-04-25 08:22
浏览 47

用文本替换DOM节点

Parsing and Editing HTML in PHP can be done using the DOMdocument and DOMnode classes. Answered in another questions is how to turn

<div>text <p>test</p> more text</div>

Into:

<div>text <a>test</a> more text</div>

Or turn it into (PHP DOMDocument question: how to replace text of a node?)

<div>text <p>and</p> more text</div>

But, how do you replace the node all together into just text, and turn it into this?

<div>text and more text</div> 
  • 写回答

1条回答 默认 最新

  • dst3605528 2016-04-25 08:22
    关注

    It took me some searching to find a generic method.

    The clue is that text itself also consists of nodes. By default, when loading a document, each continguous block of text is replaced with a single 'text node' representing it. Thus the example HTML contains three nodes;

    • a text node
    • a <p> node (containing a text node)
    • another text node

    To replace the p node, we create another text node. Then we get a list of three text nodes. Finally, to merge it back into one text node (matching a newly loaded document with the formatting of the replaced one) there is a function 'normalize' that recursively will 'clean up' after the edits, removing spurious nodes and merging adjacent text nodes.

    $text = "<div>text <p>test</p> more text</div>";
    $doc = \DOMDocument::loadHTML($text);
    $node = $doc->getElementsByTagName("div")->item(0);
    $child = $node->childNodes->item(1);
    $newNode = $doc->createTextNode("and");
    $node->replaceChild($newNode, $child);
    $node->normalize();
    // Check for correctness
    echo $doc->saveHTML();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用