How can I create a function similar to Google Buzz or Facebook, where the user types an '@' symbol followed by a username which is then turned into a link?


Input is: "Hello, @example_user!"
And the output is: "Hello, Example User!"


This, I'm sure, would be simple to do.

(I'm new to the preg_replace function, and relatively new to PHP in general.)

Thanks, ~James

Just used some gibberish as input.


$input = "Hello, @example_user5! What's your favorite past time, @dylan?\n\nHaha, @kirk\n...!";

$output = preg_replace("#@(([\w\d]){5,})+#", "<a href=\"$1\">$1</a>", $input);

echo $output;

Yes, it was simple. "[\w\d]" = "[A-Za-z0-9_]" - which I think it's enough for safe user nicknames. Also, this regex will match strings that are 5 or more characters long (works great with minimum username length). If you'll allow nicknames like "John^Dough" you should change the regex to something like "#@(([\w\d^]){5,})+#". You get the picture.

Already nicely answered.