例如,<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:从文本中删除特定域的所有超链接 https://stackoverflow.com/questions/9856933/php-remove-all-hyperlinks-of-specific-domain-from-text删除特定 url 的链接,但也删除文本。
网站位于http://php-opensource-help.blogspot.ie/2010/10/how-to-remove-hyperlink-from-string.html 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 倍。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)