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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 如何添加rel =“nofollow”到与preg_replace()的链接脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
以下功能旨在将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_r@L_304_20@_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) &amp;& (!$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,它没有在任何地方声明.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 如何添加rel =“nofollow”到与preg_replace()的链接全部内容,希望文章能够帮你解决php – 如何添加rel =“nofollow”到与preg_replace()的链接所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。