PHP头条
热点:

php自动给内容里面的a超级链接加上nofollow标签


如果你的网站正在受到垃圾留言的骚扰的话,下面的php代码也许对你会很有帮助。它的功能很简单,就是将一段字符串内容中的链接元素加上nofollow标签。代码如下:

/**
 * @param $content
 * @return null|string|string[]
 */
function addNoFollowToLinks($content) {
    return preg_replace_callback("#(<a.*?>)#i", 'addNoFollowToLink', $content);
}

/**
 * @param $input
 * @return null|string|string[]
 */
function addNoFollowToLink($input) {
    if (empty($input[1])) {
        return '';
    }

    $input = $input[1];

    if (preg_match('#rel\s*?=\s*?[\'"]?.*?nofollow.*?[\'"]?#i', $input)) {
        return $input;
    }

    preg_match('#href\s*?=\s*?[\'"]?([^\'"]*)[\'"]?#i', $input, $captures);

    if (!preg_match('#^\s*http://#', $captures[1])) {
        return $input;
    }

    $parsed = parse_url($captures[1]);
    if (!empty($GLOBALS['whitelist'])) {
        if (in_array($parsed['host'], $GLOBALS['whitelist'])) {
            return $input;
        }
    }

    $x = preg_replace('#(rel\s*=\s*([\'"]?))((?(3)[^\'"]*|[^\'" ]*))([\'"]?)#i', '\\1\\3,nofollow\\4', $input);

    if ($x != $input) {
        return $x;
    } else {
        return preg_replace('#<a#i', '<a rel="nofollow"', $input);
    }
}

使用示例:

echo addNoFollowToLinks('示例:<a href="http://www.google.com">谷歌</a><a href="http://www.phpernote.com">php程序员的笔记</a><a href="http://www.taobao.com">淘宝</a>');

注意:需要在客户端提交的最原始的内容上做这个处理,如果转义处理或其他过滤处理操作之后再加这个标签肯能会不起作用,另外显示到页面的时候也需要通过 stipslashes 函数将转义的字符(比如双引号)清理掉。

www.phpzy.comtrue/php/30813.htmlTechArticlephp自动给内容里面的a超级链接加上nofollow标签 如果你的网站正在受到垃圾留言的骚扰的话,下面的php代码也许对你会很有帮助。它的功能很简单,就是将一段字符串内容中的链接元素加...

相关文章

PHP之友评论

今天推荐