PHP Using DOMXPath to Markup Tags and Remove Nodes

I am trying to work with DOMDocument but I am facing some problems. I have a line like this:

Some Content to keep
<span class="ice-cts-1 ice-del" data-changedata="" data-cid="5" data-time="1414514760583" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
     This content should remain, but span around it should be stripped
</span> 
     Keep this content too
<span>
     <span class="ice-cts-1 ice-ins" data-changedata="" data-cid="2" data-time="1414512278297" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
         This whole node should be deleted
     </span>
</span>

      

What I want to do is if the span class is of type class ice-del

, keep the inner content but remove the span tags. If it has ice-ins

, remove all node.

If it's just an empty range <span></span>

, remove it. This is the code I have:

//this get the above mentioned string
$getVal = $array['body'][0][$a];
$dom = new DOMDocument;
$dom->loadHTML($getVal );
$xPath = new DOMXPath($dom);
$delNodes = $xPath->query('//span[@class="ice-cts-1 ice-del"]');
$insNodes = $xPath->query('//span[@class="ice-cts-1 ice-ins"]');

foreach($insNodes as $span){
    //reject these changes, so remove whole node
    $span->parentNode->removeChild($span);
}

foreach($delNodes as $span){
    //accept these changes, so just strip out the tags but keep the content
}

$newString = $dom->saveHTML();

      

So my code works to remove the entire range of a node, but how can I take a node and strip out its tags, but keep its contents?

Also, how would I just remove and remove the space? I'm sure I can do it with regex or replace, but I want to do it with dom.

thank

+3


source to share


1 answer


No, I would not recommend regex, I highly recommend using what you have right now using this beautiful HTML Parser. You can use ->replaceChild

in this case:



$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);

$spans = $xPath->query('//span');
foreach ($spans as $span) {
    $class = $xPath->evaluate('string(./@class)', $span);
    if(strpos($class, 'ice-ins') !== false || $class == '') {
        $span->parentNode->removeChild($span);
    } elseif(strpos($class, 'ice-del') !== false) {
        $span->parentNode->replaceChild(new DOMText($span->nodeValue), $span);
    }
}

$newString = $dom->saveHTML();

      

+3


source







All Articles