php给友情链接a标签加nofollow属性值

PHP 投稿 32400 0 评论

php给友情链接a标签加nofollow属性值

nofollow是一个HTML标签的属性值。这个标签的意义是告诉搜索引擎“不要追踪此网页上的链接或不要追踪此特定链接”。

网站的友情链接不想传递权重,就是将一段字符串内容中的链接元素加上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.feishuai.vip">编程学习分享</a><a href="http://www.taobao.com">淘宝</a>');

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

编程笔记 » php给友情链接a标签加nofollow属性值

赞同 (64) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽