PHP删除特定网站的链接,但保留文本


PHP remove links to specific website but keep text

例如,<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>

我一直在尝试使用preg_replace来解决这个问题。我在这里搜索了一遍,找到了解决问题的答案。

PHP的答案是:从文本中删除特定域的所有超链接会删除指向特定url的链接,但也会删除文本。

网站位于http://php-opensource-help.blogspot.ie/2010/10/how-to-remove-hyperlink-from-string.html从字符串中删除超链接,但我似乎无法修改模式,使其仅适用于特定网站。

$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();

对于那些出于性能原因害怕使用DomDocument而不是preg_replace的人,我在这与Q中链接的代码(完全删除链接的代码)之间做了一个快速测试=>DomDocument只慢了大约4倍。