例如, <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倍慢。