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?
2
Answers
There may be other ways to do it, but try the following:
Assuming that your string is embedded in a tag like:
Change your code to:
Output should be:
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
with this
(according to this example https://www.php.net/manual/en/domnode.replacechild.php#48485)