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?

Example:

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

(http://example.site/profile.php?u=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

Member Avatar for nevvermind

Just used some gibberish as input.

<?php

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

$output = preg_replace("#@(([\w\d]){5,})+#", "<a href=\"http://example.site/profile.php?u=$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.

Thanks, :D It works great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.