title: How do I linkify Twitter usernames using PHP preg_replace?
body: <p>I want to search the text property of my twitter status objects and swap out @username for <code>&lt;a href="http:/twitter.com/username"&gt;@username&lt;/a&gt;</code>. What I have tried so far looks like this:</p>
  
  <pre><code>$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/';
  $replace = '&lt;a href="http://twitter.com/\2"&gt;\1\2&lt;/a&gt;';
  $new_string = preg_replace($pattern, $replace, $text);
  </code></pre>
  
  <p>But it doesn't do any replacements. I know my reg exp is wrong but I can't figure out exactly where/why. Help?</p>
  
  <p>**Edit: ... sample data as requested?</p>
  
  <pre><code>$text = '@janesmith I like that, but my friend @johndoe said it better.';
  </code></pre>
  
  <p>Desired output: </p>
  
  <p><a href="http://twitter.com/janesmith" rel="nofollow">@janesmith</a> I like that, but my friend <a href="http://twitter.com/johndoe" rel="nofollow">@johndoe</a> said it better.</p>
  
  <p><code>***** MY FULL FUNCTION *****</code></p>
  
  <pre><code>function linkify($string, $twitter=false) {
  
      // reg exp pattern
      $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
  
      // convert string URLs to active links
      $new_string = preg_replace($pattern, "&lt;a href=\"\\0\"&gt;\\0&lt;/a&gt;", $string);
  
      if ($twitter) {
          $pattern = '/@([a-zA-Z0-9_]+)/';
          $replace = '&lt;a href="http://twitter.com/\1"&gt;@\1&lt;/a&gt;';
          $new_string = preg_replace($pattern, $replace, $new_string);
      }
  
      return $new_string;
  }
  </code></pre>