php – 如何添加rel =“nofollow”到与preg_replace()的链接
发布时间:2020-12-13 16:37:52 所属栏目:PHP教程 来源:网络整理
导读:以下功能旨在将rel =“nofollow”属性应用于所有外部链接,并且不使用内部链接,除非路径与以下定义为$my_folder的预定义根网址匹配. 所以给出变量… $my_folder = 'http://localhost/mytest/go/';$blog_url = 'http://localhost/mytest'; 和内容… a href="ht
以下功能旨在将rel =“nofollow”属性应用于所有外部链接,并且不使用内部链接,除非路径与以下定义为$my_folder的预定义根网址匹配.
所以给出变量… $my_folder = 'http://localhost/mytest/go/'; $blog_url = 'http://localhost/mytest'; 和内容… <a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator">internal cloaked link</a> <a href="http://cnn.com">external</a> 最后的结果,更换后应该是… <a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator" rel="nofollow">internal cloaked link</a> <a href="http://cnn.com" rel="nofollow">external</a> 请注意,第一个链接不会因为内部链接而被更改. 第二行的链接也是一个内部链接,但是由于它与我们的$my_folder字符串相匹配,所以它也获得了nofollow. 第三个链接是最简单的,因为它不符合blog_url,它显然是一个外部链接. 然而,在下面的脚本中,我的所有链接都得到nofollow.如何修复脚本来做我想做的事情? function save_rSEO_nofollow($content) { $my_folder = $rSEO['nofollow_folder']; $blog_url = get_bloginfo('url'); preg_match_all('~<a.*>~isU',$content["post_content"],$matches); for ( $i = 0; $i <= sizeof($matches[0]); $i++){ if ( !preg_match( '~nofollow~is',$matches[0][$i]) && (preg_match('~' . $my_folder . '~',$matches[0][$i]) || !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){ $result = trim($matches[0][$i],">"); $result .= ' rel="nofollow">'; $content["post_content"] = str_replace($matches[0][$i],$result,$content["post_content"]); } } return $content; }
尝试使其更易于阅读,之后只会使您的if规则更加复杂:
function save_rSEO_nofollow($content) { $content["post_content"] = preg_replace_callback('~<(as[^>]+)>~isU',"cb2",$content["post_content"]); return $content; } function cb2($match) { list($original,$tag) = $match; // regex match groups $my_folder = "/hostgator"; // re-add quirky config here $blog_url = "http://localhost/"; if (strpos($tag,"nofollow")) { return $original; } elseif (strpos($tag,$blog_url) && (!$my_folder || !strpos($tag,$my_folder))) { return $original; } else { return "<$tag rel='nofollow'>"; } } 提供以下输出: [post_content] => <a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator" rel=nofollow>internal cloaked link</a> <a href="http://cnn.com" rel=nofollow>external</a> 您的原始代码中的问题可能是$rSEO,它没有在任何地方声明. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |