如果你的网站正在受到垃圾留言的骚扰的话,下面的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('#rels*?=s*?['"]?.*?nofollow.*?['"]?#i', $input)) { return $input; } preg_match('#hrefs*?=s*?['"]?([^'"]*)['"]?#i', $input, $captures); if (!preg_match('#^s*https://#', $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('#(rels*=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="https://www.google.com">谷歌</a><a href="https://www.phpernote.com">php程序员的笔记</a><a href="https://www.taobao.com">淘宝</a>');
注意:需要在客户端提交的最原始的内容上做这个处理,如果转义处理或其他过滤处理操作之后再加这个标签肯能会不起作用,另外显示到页面的时候也需要通过 stipslashes 函数将转义的字符(比如双引号)清理掉。
—-想了解更多的php相关异常处理怎么解决关注<计算机技术网(www.ctvol.com)!!>
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/phpttorial/104487.html