Here's a modified version of snipe's twitterify():
<?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://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
return $ret;
}
Testing the code above with test()
...
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");
?>
...results in the following print-outs.
INPUT: "www.foo.com"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a>
INPUT: "www.foo.com fox"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a> fox
INPUT: "www.test.com fox jumped over www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">www.test.com</a><a href="http://www.foo.com" target="_blank"> fox jumped over </a>
INPUT: "fox jumped over www.test.com the fence www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">fox jumped over </a><a href="http://www.foo.com" target="_blank"> the fence </a>
Tested on ideone.
EDIT: Updated code to match new requirements