PHP remove links to specific website but keep text

2019-03-02 21:12发布

For example, <a href="http://msdn.microsoft.com/art029nr/">remove links to here but keep text</a> but <a href="http://herpyderp.com">leave all other links alone</a>

I've been trying to solve this using preg_replace. I've searched through here and found answers that solve pieces of the problem.

The answer at PHP: Remove all hyperlinks of specific domain from text removes links to a specific url but removes the text also.

The site at http://php-opensource-help.blogspot.ie/2010/10/how-to-remove-hyperlink-from-string.html removes a hyperlink from a string but I can't seem to modify the pattern so that it applies only to a specific website.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-02 22:17
$html = '...I can haz HTML?...';
$whitelist = array('herpyderp.com', 'google.com');

$dom = new DomDocument();
$dom->loadHtml($html);    
$links = $dom->getELementsByTagName('a');

foreach($links as $link){
  $host = parse_url($link->getAttribute('href'), PHP_URL_HOST);

  if($host && !in_array($host, $whitelist)){    

    // create a text node with the contents of the blacklisted link
    $text = new DomText($link->nodeValue);

    // insert it before the link
    $link->parentNode->insertBefore($text, $link);

    // and remove the link
    $link->parentNode->removeChild($link);
  }  

}

// remove wrapping tags added by the parser
$dom->removeChild($dom->firstChild);            
$dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);

$html = $dom->saveHtml();

For those scared to use DomDocument instead of preg_replace for performance reasons, I did a quick test between this and the code linked in the Q (the one that completely removes the links) => DomDocument is only ~4 times slower.

查看更多
登录 后发表回答