2013-02-11 81 views
1

例如,<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>PHP刪除鏈接到特定的網站,但保留文本

我一直在試圖解決這個使用的preg_replace。我在這裏搜索並找到解決問題的答案。

PHP: Remove all hyperlinks of specific domain from text的答案刪除指向特定網址的鏈接,但也刪除文本。

http://php-opensource-help.blogspot.ie/2010/10/how-to-remove-hyperlink-from-string.html的網站從字符串中刪除超鏈接,但我似乎無法修改該模式,因此它只適用於特定的網站。

+4

[不要使用正則表達式解析HTML](http://stackoverflow.com/a/1732454/344643)使用[XML解析器](http://us2.php.net/manual/en/class。 domdocument.php)代替。 – 2013-02-11 00:13:02

回答

1
$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倍慢。

+0

非常感謝。該網址是一個子域似乎導致了一個問題,但我可以通過輸入第一部分來解決這個問題。未刪除的唯一鏈接是使用逗號和引號的網址警告:DOMDocument :: loadHTML():htmlParseEntityRef。你知道解決這個問題的方法嗎?再次感謝。 – Danny 2013-02-11 02:23:42

+0

如果HTML格式錯誤 - 禁用錯誤(請參閱[此答案](http://stackoverflow.com/a/7082487/1058140))。我只在這裏做了一個主機檢查。如果你想對整個url執行檢查,路徑等等,請閱讀'parse_url()'的文檔頁面 – 2013-02-11 02:39:08