Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to remove certain links depending on their ID tag, but leave the content of the link. For example I want to turn

Some text goes <a href="http://www.domain.tdl/" id="remove">here</a>

to

Some text goes here

I have tried using the below.

$dom = new DOMDocument;
$dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));
$xp = new DOMXPath($dom);

foreach($xp->query('//a[contains(@id="remove")]') as $oldNode) {
$revised = strip_tags($oldNode);
}

$revised = mb_substr($dom->saveXML($xp->query('//body')->item(0)), 6, -7, "UTF-8");
echo $revised;

roughly taken from here but it just spits back the same content of $html.

Any idea's on how I would achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
549 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's my function for that:

function DOMRemove(DOMNode $from) {
    $sibling = $from->firstChild;
    do {
        $next = $sibling->nextSibling;
        $from->parentNode->insertBefore($sibling, $from);
    } while ($sibling = $next);
    $from->parentNode->removeChild($from);    
}

So this:

$dom->loadHTML('Hello <a href="foo"><span>World</span></a>');
$a = $dom->getElementsByTagName('a')->item(0); // get first
DOMRemove($a);

Should give you:

Hello <span>World</span>

To get nodes with a specific ID, use XPath:

$xpath = new DOMXpath($dom);
$node = $xpath->query('//a[@id="something"]')->item(0); // get first
DOMRemove($node);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...