PHP DOM removing the tag (not content)

Go To StackoverFlow.com

1

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

2012-04-04 00:02
by dr.linux


4

Try the following:

if($nodes->item(0)) {
    $node = $nodes->item(0);
    $node->parentNode->replaceChild(new DOMText($node->textContent), $node); 
} 
2012-04-04 00:07
by Tim Cooper


-1

Or, Use simple techniques to do simple things.

Here is an alternative to strip_tags()

preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)
2012-04-04 00:14
by Starx
preg_replace causes some performance problems with my software but thanks for your opinion - dr.linux 2012-04-04 00:27
Regex is the worst way to handle html - mopsyd 2018-04-23 23:35


-2

"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>");
2012-04-04 00:09
by kingcoyote
actually i've many tags but i want to unstrip some tags. this function strips all tags something like div, p, b, blablabla. but thanks for your opinion - dr.linux 2012-04-04 00:29
The second parameter can specify which tags to leave. For instance, to leave in span, p and div:

echo strip_tags($string, '<span><p><div>");
< - kingcoyote 2012-04-04 00:34
I'm sorry to downvote you but I feel compelled to, because strip_tags with certain tags permitted is a security problem because it does not allow to strip attributes - cmc 2014-02-28 09:51
Ads