How to add rel=“nofollow” to links with preg_replace()

后端 未结 7 2076

The function below is designed to apply rel=\"nofollow\" attributes to all external links and no internal links unless the path matches a predefined root URL de

7条回答
  •  温柔的废话
    2020-12-09 20:33

    Try to make it more readable first, and only afterwards make your if rules more complex:

    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'>";
        }
    }
    

    Gives following output:

    [post_content] =>
      internal
      internal cloaked link    
      external
    

    The problem in your original code might have been $rseo which wasn't declared anywhere.

提交回复
热议问题