geoidesic
geoidesic

Reputation: 5053

How can I add an element into the middle of a text node's text?

Given the following HTML:

$content = '<html>
 <body>
  <div>
   <p>During the interim there shall be nourishment supplied</p>
  </div>
 </body>
</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>

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();

However, this outputs literal html entities so it renders like this in the browser:

During the <span>interim</span> there shall be nourishment supplied

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?

Upvotes: 3

Views: 867

Answers (3)

Alf Eaton
Alf Eaton

Reputation: 5463

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);

Upvotes: 3

Marcus Harrison
Marcus Harrison

Reputation: 869

In order to do this, you must use the DOMString's splitText interface. This accepts an offset, which can be retrieved by using strpos:

$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->childNodes->item(0);
        $text->splitText(strpos($text->textContent, "interim"));
        $text2 = $element->childNodes->item(1);
        $text2->splitText(strpos($text2->textContent, " "));
        $element->removeChild($text2);
        $span = $dom->createElement("span");
        $span->appendChild($dom->createTextNode("interim"));
        $element->insertBefore($span, $element->childNodes->item(1));
    }
}
echo $dom->saveHTML();

Edits: having just tested it, I realise I hadn't removed the original "interim" in the second text node. Edited this answer to do that. I have also edited this code to be as compatible with old versions of PHP as I can think of making it: as I don't run an old version of PHP it isn't possible for me to test that.

Upvotes: 0

splash58
splash58

Reputation: 26153

Create a new DomDocument with modified element and replace the old one

 foreach ($elements as $element) {
   $text = $element->nodeValue;

   $el = new DomDocument();
   $el->loadHTML('<iframe>'. str_replace('interim','<span>interim</span>',$text) . '</iframe>');
   $new = $dom->importNode($el->getElementsByTagName('iframe')->item(0), true);
   unset($el);

   $element->parentNode->replaceChild($new, $element);
 }

Upvotes: 0

Related Questions