正则表达式有助于将rel =“nofollow”添加到匹配预定义URL模式的链接

时间:2011-01-26 18:13:26

标签: php regex

下面的函数会解析从过滤器传递的内容,并将 rel =“nofollow” 添加到它找到的所有外部链接中,并且当前会跳过所有内部链接。< / p>

假设我在变量中定义了文件夹路径,请说...

$my_folder = "http://mysite.com/recommends/";

我如何扩充功能,以便它也将nofollow广告到与此模式匹配的链接?这些可能是内部链接,这些将是我想要在这个例子中无法使用的唯一内部链接,所以它们需要以某种方式从内部链接正则表达式位被例外。

add_filter('wp_insert_post_data', 'new_content' );
function new_content($content) {
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( '~'.get_bloginfo('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;

}

PS:感谢来自WSX的Backie获取当前的功能代码......

1 个答案:

答案 0 :(得分:1)

我无法尝试这个,因为我不是WP用户,但假设你的内部循环将$matches[0][$i]定义为当前要比较的网址:


add_filter('wp_insert_post_data', 'new_content' );
    function new_content($content) {
    $my_folder =  "http://mysite.com/recommends/";
    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( '~'.get_bloginfo('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;
}

编辑:可能必须在$ my_folder周围添加一个preg_quote,我只是有点困惑,因为它没有为get_bloginfo('url')

相关问题