优选主流主机商
任何主机均需规范使用

织梦CMS如何用PHP正则实现文章外链自动添加nofollow属性

“nofollow” 标签是Google、Yahoo和微软公司前几年一起提出的一个标签,链接加上这个标签后就不会被计算权值,搜索引擎支持nofollow属性,在很大程度上抑制博客或论坛的垃圾留言。对站长来说是一件大好事。

nofollow的作用

nofollow主要有三个作用:

1.防止不可信的内容,最常见的是博客上的垃圾留言与评论中为了获取外链的垃圾链接,为了防止页面指向一些拉圾页面和站点。

2.付费链接:为了防止付费链接影响Google的搜索结果排名,Google建议使用nofollow属性。

3.引导爬虫抓取有效的页面:避免爬虫抓取一些无意义的页面,影响爬虫抓取的效率。

有时候需要对文章进行自动处理nofollow,防止权重流失,对于做网站优化seo的来说很重要。

$host为不需要进行处理的站点域名,否则全部自动加上nofollow。

首先正则出a标签和href,然后进行每一层级判断处理。

如果是外链,而且没有nofollow就自动加上。

  1. /**
  2. * 自动处理外链加上rel=”nofollow”
  3. */
  4. function webOutUrlDispose($html)
  5. {
  6. $host = [‘www.jb51.net’, $_SERVER[‘HTTP_HOST’]];//站点host
  7. $pattern = ‘/ ]*>.*<\ a=””>/’ ;
  8. preg_match_all($pattern, $html, $matches);
  9. for ($i = 0; $i < count($matches[0]); $i++) {
  10. if (!strstr($matches[1][$i], ‘://’)) {
  11. continue;
  12. }
  13. $array = parse_url($matches[1][$i]);
  14. if (in_array($array[‘host’], $host)) {
  15. continue;
  16. }
  17. if (!strstr($matches[0][$i], ‘rel=’)) {
  18. $yuan = $matches[0][$i];
  19. $matches[0][$i] = str_replace(‘<a’, ‘<a rel=”nofollow”‘, $matches[0][$i]);
  20. $html = str_replace($yuan, $matches[0][$i], $html);
  21. }
  22. }
  23. return $html;
  24. }

dedecms使用的话,需要在/include/extend.func.php下新增如上方法

模板调用:

{dede:field.body function=’webOutUrlDispose(@me)’/}

以上方法没有测试,各位请自行测试,织梦CMS利用php正则让文章的外链自动加nofollow。

未经允许不得转载:搬瓦工中文网 » 织梦CMS如何用PHP正则实现文章外链自动添加nofollow属性