title: How to add rel="nofollow" to links with preg_replace()
body: <p>The function below is designed to apply <code>rel="nofollow"</code> attributes to all external links and no internal links unless the path matches a predefined root URL defined as <code>$my_folder</code> below.</p>
  
  <p>So given the variables...</p>
  
  <pre><code>$my_folder = 'http://localhost/mytest/go/';
  $blog_url = 'http://localhost/mytest';
  </code></pre>
  
  <p>And the content...</p>
  
  <pre><code>&lt;a href="http://localhost/mytest/"&gt;internal&lt;/a&gt;
  
  &lt;a href="http://localhost/mytest/go/hostgator"&gt;internal cloaked link&lt;/a&gt;
  
  &lt;a href="http://cnn.com"&gt;external&lt;/a&gt;
  </code></pre>
  
  <p>The end result, after replacement should be...</p>
  
  <pre><code>&lt;a href="http://localhost/mytest/"&gt;internal&lt;/a&gt;
  
  &lt;a href="http://localhost/mytest/go/hostgator" rel="nofollow"&gt;internal cloaked link&lt;/a&gt;
  
  &lt;a href="http://cnn.com" rel="nofollow"&gt;external&lt;/a&gt;
  </code></pre>
  
  <p>Notice that the first link is not altered, since its an internal link.</p>
  
  <p>The link on the second line is also an internal link, but since it matches our <code>$my_folder</code> string, it gets the <code>nofollow</code> too.</p>
  
  <p>The third link is the easiest, since it does not match the <code>blog_url</code>, its obviously an external link.</p>
  
  <p>However, in the script below, ALL of my links are getting <code>nofollow</code>. How can I fix the script to do what I want?</p>
  
  <pre><code>function save_rseo_nofollow($content) {
  $my_folder =  $rseo['nofollow_folder'];
  $blog_url = get_bloginfo('url');
      preg_match_all('~&lt;a.*&gt;~isU',$content["post_content"],$matches);
      for ( $i = 0; $i &lt;= sizeof($matches[0]); $i++){
          if ( !preg_match( '~nofollow~is',$matches[0][$i])
              &amp;&amp; (preg_match('~' . $my_folder . '~', $matches[0][$i]) 
                 || !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){
              $result = trim($matches[0][$i],"&gt;");
              $result .= ' rel="nofollow"&gt;';
              $content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
          }
      }
      return $content;
  }
  </code></pre>