以下功能旨在将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>
最后的结果,更换后应该是…
第二行的链接也是一个内部链接,但是由于它与我们的$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('~<(a\s[^>]+)>~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'>";
- }
- }
提供以下输出: