pipedreams2
pipedreams2

Reputation: 628

Replace HTML in existing DOMNode

I have looked around on here for a proper answer for this but cannot find anything reasonable. I am grabbing text from within elements of a certain class and bolding all caps. I can get the text and apply my changes but when inserting back into the DOMNode PHP decides to reformat tags making it useless as HTML. If u dump the $replaced string it is fine it is getting stripped when being saved to the node. Does anyone have a reasonable solution for this??

I should mention, I am trying to replace the text currently in this node not append.

        $dom        = new DOMDocument();
        $dom->loadHTML($output);

        $search     = new DomXPath($dom);
        $class      = "lead";

        $nodes                  = $search->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");
        $leadContent            = $nodes[0]->nodeValue;
        $replaced               = preg_replace('/([A-Z])/', '<strong>$0</strong>', $leadContent);
        $nodes[0]->nodeValue    = $replaced;
        $output                 = $dom->saveHTML();

Upvotes: 1

Views: 66

Answers (1)

pipedreams2
pipedreams2

Reputation: 628

Found a solution using a document fragment in case anyone is interested.

Just removed current text from node and replaced with a document fragment. Runs through each node of lead class to check if it is ALSO a paragraph tag.

$dom->loadHTML($output);

$search     = new DomXPath($dom);
$lead       = "lead";

$nodes      = $search->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $lead ')]");

foreach( $nodes as $node )
{
    if( $node->tagName == "p" )
    {
        $leadClass              = $node->nodeValue;
        $replaced               = preg_replace('/([A-Z])/', '<strong>$0</strong>', $leadClass);
        $node->nodeValue        = '';
        $temp                   = $dom->createDocumentFragment();

        $temp->appendXML($replaced);
        $node->appendChild($temp);
    }
}

$output = $dom->saveHTML();

Upvotes: 1

Related Questions