dr.linux
dr.linux

Reputation: 752

PHP DOM removing the tag (not content)

$mystring="This is mystring. <a href='http://www.google.com'>Google.</a>"; 
$dom = new DOMDocument; 
$dom->loadHTML($mystring); 
$xPath = new DOMXPath($dom); 
$nodes = $xPath->query('//a');
if($nodes->item(0)) { 
    $nodes->item(0)->parentNode->removeChild($nodes->item(0)); 
} 
echo $dom->saveHTML();  

I want to get output:

This is mystring. Google.

But i got just:

This is mystring.

Upvotes: 1

Views: 2116

Answers (3)

Starx
Starx

Reputation: 78981

Or, Use simple techniques to do simple things.

Here is an alternative to strip_tags()

preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)

Upvotes: -1

kingcoyote
kingcoyote

Reputation: 1146

"Google" is a child of the node you are trying to remove. So this behavior is expected. I think what you want is to use PHP's strip_tags function.

echo strip_tags("This is mystring. <a href='http://www.google.com'>Google.</a>");

Upvotes: -2

user142162
user142162

Reputation:

Try the following:

if($nodes->item(0)) {
    $node = $nodes->item(0);
    $node->parentNode->replaceChild(new DOMText($node->textContent), $node); 
} 

Upvotes: 4

Related Questions