Home > Mobile >  Using DomDocument to Replace an <a> tag with Text
Using DomDocument to Replace an <a> tag with Text

Time:01-13

I'm looking to replace <a> tag in string with some text. My code is as follows

$string = 'This link <a href="somedomain.com">Some Domain</a> needs to be removed';

        $domdocument = new \DOMDocument();
        $domdocument->loadHTML($string, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
        $link = $domdocument->getElementsByTagName('a')[0];

        $replacement_link = $domdocument->createTextNode("HELLO WORLD");
        $domdocument->appendChild($replacement_link);
        $domdocument->replaceChild($link, $replacement_link);
        $output = $domdocument->saveHTML();
        dd($output);

// Expected output: 'This link HELLO WORLD needs to be removed'

However, I get the $string back as output, without any replacement. Where am I going wrong?

CodePudding user response:

maybe is the order of the parameters?

replaceChild($newelement, $element);

CodePudding user response:

There may be other ways to do it, but try the following:

Assuming that your string is embedded in a tag like:

$string = '<p>This link <a href="somedomain.com">Some Domain</a> needs to be removed</p>';

Change your code to:

$domdocument = new \DOMDocument();
$domdocument->loadHTML($string, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
$link = $domdocument->getElementsByTagName('a')[0];

#new part:
$linkParent = $domdocument->getElementsByTagName('p')[0];
$link->textContent = "HELLO WORLD";
$linkParent->textContent = $linkParent->nodeValue;
$output = $domdocument->saveHTML();
echo($output);

Output should be:

<p>This link HELLO WORLD needs to be removed</p>

CodePudding user response:

It seems that replacement node should not be appended to document before replacing. According to docs: This function replaces the child child with the passed new node. If the node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Instead, it should be imported into the document. Try to replace this line

$domdocument->appendChild($replacement_link);

with this

$domdocument->importNode($replacement_link, true);

(according to this example https://www.php.net/manual/en/domnode.replacechild.php#48485)

  • Related