网站内容通常会有很多外部链接,如果每个都手动修改nofollow标签很麻烦,这里分享给大家这篇利用正则表达式自动判断链接是否为外链,如果是外部链接就自动加上nofollow标签的教程。这样可以很好的优化网站链接,减少网站传递权重,也无需手动添加修改。
function tin_seo_wl( $content ) {
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$srcUrl = get_option('siteurl');
for ($i=0; $i < count($matches); $i++)
{
$tag = $matches[$i][0];
$tag2 = $matches[$i][0];
$url = $matches[$i][0];
$noFollow = '';
$pattern = '/target\s*=\s*"\s*_blank\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' target="_blank" ';
$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' rel="nofollow" ';
$pos = strpos($url,$srcUrl);
if ($pos === false) {
$tag = rtrim ($tag,'>');
$tag .= $noFollow.'>';
$content = str_replace($tag2,$tag,$content);
}
}
}
}
$content = str_replace(']]>', ']]>', $content);
return $content;
}这段代码是WordPress技术教程内学习到的,代码只用到正则表达式,应该是通用的。
我们只需要修改下传递的变量为自己需要处理的变量就可以了,这样所有的外部链接就会自动加上 nofollow 标签。

