2013-07-13 82 views
1

我需要將rel="nofollow"添加到所有外部鏈接(不通向我的網站或其子域)。PHP正則表達式將rel =「nofollow」添加到外部鏈接

我已經在兩個步驟中完成這一點,在第一予添加rel="nofollow"使用以下正則表達式的鏈接(甚至內部鏈接):

<a href="http([s]?)://(.*?)" 

然後在第二個步驟I消除rel="nofollow"用於內部鏈路(

<a href="http([s]?)://(www\.|forum\.|blog\.)mysite.com(.*?)" rel="nofollow" 

如何,我只在一個步驟做到這一點:使用下面的正則表達式我的網站及其子域)?可能嗎?

+0

如何使用HTML解析器? – Antony

+0

更好的是,如何使用搜索功能?可能的[RegEx表達式查找href鏈接並向其添加NoFollow](http://stackoverflow.com/q/2450985)或[如何將rel =「nofollow」添加到preg \ _replace()]的鏈接http://stackoverflow.com/q/5037592) – mario

回答

-1

更換

(<a href="https?://)((?:(?!\b(mysite\.com|www\.mysite\.com|forum\.mysite\.com)\b)[^"])+)" 

\1\2" rel="nofollow" 
2

的DOM方法:

$doc = new DOMDocument(); 
@$doc -> loadHTMLFile($url); // url of the html file 
$links = $doc->getElementsByTagName('a'); 

foreach($links as $link) { 
    $href = $link->getAttribute('href'); 
    if (preg_match('~^https?://(?>[^/m]++|m++(?!ysite.com\b))*~', $href)) 
     $link->setAttribute('rel', 'nofollow'); 
} 

$doc->saveHTMLFile($url); 
相關問題