熟悉SEO的朋友都知道,對于網站外部鏈接失效的情況如果鏈接帶有rel="nofollow"屬性可以避免不必要的損失。本文就以實例形式演示了PHP實現對站點內容外部鏈接的過濾方法。具體如下:
問題描述:原來站內很多文章都是摘錄的外部文章,文章里很多鏈接要么是時間久了失效了,要么就是一些測試的網址,如:http://localhost/ 之類的,鏈接多了的話,就形成站內很多死鏈接,這對SEO優化是很不利的。
解決方法:需要對站點內的內容進行過濾,將不是內部鏈接的鏈接加上 rel="nofollow"屬性。
本文借鑒了wordpress的過濾外部鏈接的函數,將其改一下即可使用。
function content_nofollow($content,$domain){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,$domain)===false )
$content=str_replace('href="'.$val.'"', 'href="'.$val.'" rel="external nofollow" ',$content);
}
}
preg_match_all('/src="(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,$domain)===false )
$content=str_replace('src="'.$val.'"', 'src="'.$val.'" rel="external nofollow" ',$content);
}
}
return $content; }
新聞熱點
疑難解答