自动给垃圾链接加nofollow的php代码

1. 海外社媒客户开发工具【免费】了,帮你从GG/FB/Ins/谷歌地图上免费获取客户

2. WhatsApp 聊天记录保险【99元/年】,聊天记录不怕丢。自带翻译、多开,号码抓取、群发

3. 外贸网站搭建、谷歌SEO、社媒运营、企业WhatsApp管理、外贸管理软件、AI应用,【联系我】

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

<?php

$GLOBALS[‘whitelist’] = array(‘www.jiadingqiang.com’, ‘www.seoshare.net’);

// finds all the links in $str and processes them using fixLink()
function noFollowLinks($str)
{
// replaces every link with the version provided by fixLink()
return preg_replace_callback(
“#(<a.*?>)#i”,
create_function(‘$matches’, ‘return fixLink($matches[1]);’),
$str);
}

// receives a string that contains a link such as <a href=”http://too.much.spam/”>
// and adds the ref=”nofollow” attribute if the domain isn’t in the white list
function fixLink($input)
{
// retrieve the whitelist from the config file
$whitelist = $GLOBALS[‘whitelist’];

// if the link in $input already contains ref=”nofollow”, return it as it is
if (preg_match(‘#rel\s*?=\s*?[\'”]?.*?nofollow.*?[\'”]?#i’, $input))
{
return $input;
}

// extract the URL from $input
preg_match(‘#href\s*?=\s*?[\'”]?([^\'”]*)[\'”]?#i’, $input, $captures);

// $href will contain the extracted URL, such as http://seophp.example.com
$href = $captures[1];

// if URL doesn’t contain http://, assume it’s a local link
if (!preg_match(‘#^\s*http://#’, $href))
{
return $input;
}

// extract the host name of the URL, such as seophp.example.com
$parsed = parse_url($href);
$host = $parsed[‘host’];

// if the URL is in the whitelist, send $input back as it is
if (in_array($host, $whitelist))
{
return $input;
}

// assuming the URL already has a rel attribute, change its value to nofollow
$x = preg_replace(‘#(rel\s*=\s*([\'”]?))((?(3)[^\'”]*|[^\'” ]*))([\'”]?)#i’,
‘\\1\\3,nofollow\\4’, $input);

// if the string has been modified, it means it already had a rel attribute,
// whose value has been changed to nofollow, so we return the new version
if ($x != $input)
{
return $x;
}
// if the link in the input string doesn’t have ref attribute, we add it
else
{
return preg_replace(‘#<a#i’, ‘<a rel=”nofollow”‘, $input);
}
}

?>

 

使用方法也很简单

<?php

echo noFollowLinks(‘<p>Hello! Take a look at <a href=”http://www.jiadingqiang.com”>google seo</a>!</p>’);

echo noFollowLinks(‘<p>Hello! Take a look at <a href=”http://www.baidu.com”>baidu</a>!</p>’);

?>

最终的效果是,所有不在$GLOBALS[‘whitelist’]中的域名网址都会加上nofollow标签。

1. 海外社媒客户开发工具【免费】了,帮你从GG/FB/Ins/谷歌地图上免费获取客户

2. WhatsApp 聊天记录保险【99元/年】,聊天记录不怕丢。自带翻译、多开,号码抓取、群发

3. 外贸网站搭建、谷歌SEO、社媒运营、企业WhatsApp管理、外贸管理软件、AI应用,【联系我】

微信扫一扫 或 点击链接联系我

仍有疑问,点击 链接,加个 微信 好友,一起交流。

《自动给垃圾链接加nofollow的php代码》有13条评论

  1. 我想问一下这个功能是适合所有php程序吗?有没有限制的?
    还有在使用方法方面,是直接在页面代码头部引用这2段代码吗?

发表评论