Add Nofollow to Links with PHP
If you’re creating your own blogging or forum platform using PHP, you’ll find that search engine spammers absolutely love to exploit those means of communication by spamming links to their sites. While a spam filter is a great way to combat this problem, occasionally even the best spam filters let a few spam posts through. At that point, you don’t want your site authority being imparted to a spammy site (say a Viagra or Cialis reseller!). Your best bet is rel=nofollow.
The Code
This code uses simple regular expressions to add the rel=nofollow attribute to the passed in anchor string.
//$str: The anchor string that will be altered
//$nofollow: The rel attribute values you wish to have attached to the anchor
function makeNoFollow(&$str, $nofollow){
//See if there is already a "rel" attribute
if(strpos($str, "rel")){
$pattern = "/rel=([\"'])([^\\1]+?)\\1/";
$replace = "rel=\\1\\2 $nofollow\\1";
}
else{
$pattern = "/<a /";
$replace = "<a rel=\"$nofollow\" ";
}
$str = preg_replace($pattern, $replace, $str);
}
Example
<html>
<head>
<title>NoFollow Append</title>
</head>
<body>
<?php
$link = "<a rel='external' href='www.linktomyspamsite.com'>I swear this isn't spam!</a>";
echo "Before: " . $link . "<br />\n";
function makeNoFollow(&$str, $nofollow){
//See if there is already a "rel" attribute
if(strpos($str, "rel")){
$pattern = "/rel=([\"'])([^\\1]+?)\\1/";
$replace = "rel=\\1\\2 $nofollow\\1";
}
else{
$pattern = "/<a /";
$replace = "<a rel=\"$nofollow\" ";
}
$str = preg_replace($pattern, $replace, $str);
}
makeNoFollow($link, "nofollow");
echo "After: " . $link;
?>
</body>
</html>
The code first sees if there is already a rel attribute attached to the anchor. (For example, rel=”external”). If so, it appends the $nofollow string to the end of the rel attribute value list before the ending quote. If not, it places rel= followed by the $nofollow string immediately after the anchor tag is opened.
Related Posts:


Great solution. Simple and light. Thank you, Joseph.
Glad it was useful. Thanks for stopping by!
What to do if more than one link appears ?
At that point, you’d need to incorporate an XML parser along with the script. This script assumes one instance of an anchor tag.
Perfect. Worked pretty well.
This is exactly what i was looking for. Works fine. Thanks for sharing!
Hi Joseph,
I’m trying to implement an external link “nofollow” on my site’s newsfeed. It’s a PHP include script from rssinclude
and it feeds only from news.google — how can I add nofollow for all their stories? So far, you are the only person that has come close to a solution from what I’ve seen in the internet searches.