PHP实现对站点内容外部链接的过滤方法

yipeiwu_com5年前PHP代码库

熟悉SEO的朋友都知道,对于网站外部链接失效的情况如果链接带有rel="nofollow"属性可以避免不必要的损失。本文就以实例形式演示了PHP实现对站点内容外部链接的过滤方法。具体如下:

问题描述:原来站内很多文章都是摘录的外部文章,文章里很多链接要么是时间久了失效了,要么就是一些测试的网址,如:http://localhost/ 之类的,链接多了的话,就形成站内很多死链接,这对SEO优化是很不利的。

解决方法:需要对站点内的内容进行过滤,将不是内部链接的链接加上 rel="nofollow"属性

本文借鉴了wordpress的过滤外部链接的函数,将其改一下即可使用。

具体代码如下:

//外部链接增加nofllow $content 内容 $domain 当前网站域名
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;
}

调用的时候很好调用,如下是调用演示

$a['content'] = content_nofollow($a['content'],$domain);  //将文章内容里的链接增加nofllow属性

 
注意!这里过滤的域名需要是不带“/”的,如//www.jb51.net,这样才可以很好的过滤。

相信本文所述的方法对大家的PHP项目开发有一定的借鉴价值。

相关文章

php set_time_limit()函数的使用详解

语法 : void set_time_limit (int seconds)说明 : 设定一个程式所允许执行的秒数,如果到达限制的时间,程式将会传回错误。它预设的限制时间是30秒,max...

PHP错误Parse error: syntax error, unexpected end of file in test.php on line 12解决方法

今天在写PHP程序的时候总是出现这样的错误:Parse error: syntax error, unexpected end of file in *.php on line *,然后...

PHP 常用时间函数资料整理

php常用的时间函数 测试环境:php5.3.29 unix时间戳(从Unix 纪元(January 1 1970 00:00:00 GMT)到给定时间的秒数。)。以下简称时间戳。 返回...

ThinkPHP写第一个模块应用

找到项目文件夹下面的Lib/Action这个目录,在下面有个创建好的例子IndexAction.class.php,加入我们创建的是admin这个项目,那么./admin/Lib/Act...

PHP基于工厂模式实现的计算器实例

本文实例讲述了PHP基于工厂模式实现的计算器。分享给大家供大家参考。具体如下: abstract class Calculator { private $number1; pr...