php - Replacing a DOM node with text -
parsing , editing html in php can done using domdocument
, domnode
classes. answered in questions how turn
<div>text <p>test</p> more text</div>
into:
<div>text <a>test</a> more text</div>
or turn (php domdocument question: how replace text of node?)
<div>text <p>and</p> more text</div>
but, how replace node text, , turn this?
<div>text , more text</div>
it took me searching find generic method.
the clue text consists of nodes. default, when loading document, each continguous block of text replaced single 'text node' representing it. example html contains 3 nodes;
- a text node
- a <p> node (containing text node)
- another text node
to replace p node, create text node. list of 3 text nodes. finally, merge 1 text node (matching newly loaded document formatting of replaced one) there function 'normalize' recursively 'clean up' after edits, removing spurious nodes , 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 correctness echo $doc->savehtml();
Comments
Post a Comment