PHP:从元素中删除超链接,但保留文本和类


PHP: Remove a hyperlink from element but retain the text and class

我需要处理DOM并删除指向特定网站的所有超链接,同时保留底层文本。因此,一个叫<a href="abc.com">text</a>的东西变成了text。根据这条线索,我写了这样的文章:

$as = $dom->getElementsByTagName('a');
for ($i = 0; $i < $as->length; $i++) {
    $node = $as->item($i);
    $link_href = $node->getAttribute('href');
    if (strpos($link_href,'offendinglink.com') !== false) {
        $cl = $node->getAttribute('class');
        $text = new DomText($node->nodeValue);
        $node->parentNode->insertBefore($text, $node);
        $node->parentNode->removeChild($node);
        $i--;
    }
}

这很好,只是我还需要保留属于有问题的<a>标记的类,并可能将其转换为<div><span>。因此,我需要这个:

<a href="www.offendinglink.com" target="_blank" class="nice" id="nicer">text</a>

变成这样:

<div class="nice">text</div>

添加新元素后(如我的代码片段中),我如何访问它?

quote"添加新元素后,我如何访问它(就像在我的代码片段中一样)?"-我认为您的元素在$text中。。无论如何,如果你需要保存类和textContent,但不保存其他,我认为这应该有效

foreach($dom->getElementsByTagName('a') as $url){
    if(parse_url($url->getAttribute("href"),PHP_URL_HOST)!=='badsite.com')    {
        continue;
    }
    $ele = $dom->createElement("div");
    $ele->textContent = $url->textContent;
    $ele->setAttribute("class",$url->getAttribute("class"));
    $url->parentNode->insertBefore($ele,$url);
    $url->parentNode->removeChild($url);
}

测试解决方案:

<?php
$str = "<b>Dummy</b> <a href='http://google.com' target='_blank' class='nice' id='nicer'>Google.com</a> <a href='http://yandex.ru' target='_blank' class='nice' id='nicer'>Yandex.ru</a>";
$doc = new DOMDocument();
$doc->loadHTML($str);
$anchors = $doc->getElementsByTagName('a');
$l = $anchors->length;
for ($i = 0; $i < $l; $i++) {
    $anchor = $anchors->item(0);
    $link = $doc->createElement('div', $anchor->nodeValue);
    $link->setAttribute('class', $anchor->getAttribute('class'));
    $anchor->parentNode->replaceChild($link, $anchor);
}
echo preg_replace(['/^'<'!DOCTYPE.*?<html><body>/si', '!</body></html>$!si'], '', $doc->saveHTML());

或者看runnable。