April 4, 2012

php DOM removing the tag (not content)

Question by dr.linux

$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.

Answer by Tim Cooper

Try the following:

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

Answer by Starx

Or, Use simple techniques to do simple things.

Here is an alternative to strip_tags()

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!