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. February 26, 2011
About the Author:

Joseph is the lead developer of Vert Studios Follow Joseph on Twitter: @Joe_Query
Subscribe to the blog: RSS
Visit Joseph's site: joequery.me