<?php
function twitterify($ret) {
  //
  // Replace all text that precedes a URL with an HTML anchor
  // that hyperlinks the URL and shows the preceding text as
  // the anchor text.
  // 
  // e.g., "hello world www.test.com" becomes
  // <a href="www.test.com" target="_blank">hello world</a>
  //
  $ret = preg_replace("#(.*?)(http://)?(www\.[^ \"\t\n\r<]+)#", "<a href=\"http://\\3\" target=\"_blank\">\\1</a>", $ret);

  // if anchor text is empty, insert anchor's href
  $ret = preg_replace("#(<a href=\"(\w+://)?([^\"]+)\"[^>]+>)(</a>)#", "\\1\\3\\4", $ret);

  $ret = preg_replace("/@(\w+)/", "<a href=\"http://w...content-available-to-author-only...r.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
  $ret = preg_replace("/#(\w+)/", "<a href=\"http://s...content-available-to-author-only...r.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
  return $ret;
}

function test($str) {
  print "INPUT:  \"" . $str . "\"\nOUTPUT: " . twitterify($str) . "\n\n";
}
// tests
test("www.foo.com");
test("www.foo.com  fox");
test("www.test.com  fox jumped over  www.foo.com");
test("fox jumped over  www.test.com   the fence   www.foo.com");
?>