php – 如何添加rel =“nofollow”到与preg_replace()的链接

前端之家收集整理的这篇文章主要介绍了php – 如何添加rel =“nofollow”到与preg_replace()的链接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下功能旨在将rel =“nofollow属性应用于所有外部链接,并且不使用内部链接,除非路径与以下定义为$my_folder的预定义根网址匹配.

所以给出变量…

  1. $my_folder = 'http://localhost/mytest/go/';
  2. $blog_url = 'http://localhost/mytest';

内容

  1. <a href="http://localhost/mytest/">internal</a>
  2.  
  3. <a href="http://localhost/mytest/go/hostgator">internal cloaked link</a>
  4.  
  5. <a href="http://cnn.com">external</a>

最后的结果,更换后应该是…

  1. <a href="http://localhost/mytest/">internal</a>
  2.  
  3. <a href="http://localhost/mytest/go/hostgator" rel="nofollow">internal cloaked link</a>
  4.  
  5. <a href="http://cnn.com" rel="nofollow">external</a>

请注意,第一个链接不会因为内部链接而被更改.

第二行的链接也是一个内部链接,但是由于它与我们的$my_folder字符串相匹配,所以它也获得了nofollow.

第三个链接是最简单的,因为它不符合blog_url,它显然是一个外部链接.

然而,在下面的脚本中,我的所有链接都得到nofollow.如何修复脚本来做我想做的事情?

  1. function save_rSEO_nofollow($content) {
  2. $my_folder = $rSEO['nofollow_folder'];
  3. $blog_url = get_bloginfo('url');
  4. preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
  5. for ( $i = 0; $i <= sizeof($matches[0]); $i++){
  6. if ( !preg_match( '~nofollow~is',$matches[0][$i])
  7. && (preg_match('~' . $my_folder . '~',$matches[0][$i])
  8. || !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){
  9. $result = trim($matches[0][$i],">");
  10. $result .= ' rel="nofollow">';
  11. $content["post_content"] = str_replace($matches[0][$i],$result,$content["post_content"]);
  12. }
  13. }
  14. return $content;
  15. }
尝试使其更易于阅读,之后只会使您的if规则更加复杂:
  1. function save_rSEO_nofollow($content) {
  2. $content["post_content"] =
  3. preg_replace_callback('~<(a\s[^>]+)>~isU',"cb2",$content["post_content"]);
  4. return $content;
  5. }
  6.  
  7. function cb2($match) {
  8. list($original,$tag) = $match; // regex match groups
  9.  
  10. $my_folder = "/hostgator"; // re-add quirky config here
  11. $blog_url = "http://localhost/";
  12.  
  13. if (strpos($tag,"nofollow")) {
  14. return $original;
  15. }
  16. elseif (strpos($tag,$blog_url) && (!$my_folder || !strpos($tag,$my_folder))) {
  17. return $original;
  18. }
  19. else {
  20. return "<$tag rel='nofollow'>";
  21. }
  22. }

提供以下输出

  1. [post_content] =>
  2. <a href="http://localhost/mytest/">internal</a>
  3. <a href="http://localhost/mytest/go/hostgator" rel=nofollow>internal cloaked link</a>
  4. <a href="http://cnn.com" rel=nofollow>external</a>

您的原始代码中的问题可能是$rSEO,它没有在任何地方声明.

猜你在找的PHP相关文章