vasanth.v
vasanth.v

Reputation: 213

Regular expression to find and replace @ mentions like twitter

I am developing a PHP application which needs a regular expression to replace the @ mentions like twitter. Also the regular expression should satisfy the following needs.

  1. if there is just @ and nothing before and after that then it should not be replaced.
  2. @ in the emails should not be replaced. For eg. [email protected] should not be replaced.
  3. Only strings like @sam or @example should be replaced like <a href="http://twitter.com/sam">@sam</a> and <a href="http://twitter.com/example">@example</a>

Please help. Thanks in advance.

Upvotes: 1

Views: 3913

Answers (3)

Mathieu Rodic
Mathieu Rodic

Reputation: 6762

As twitter can contain up to 15 characters, you could write it like this to avoid some bugs:

$tweet = preg_replace("/(^\w)@(\w{1,15})/i", "\\1<a ref=\"http://twitter.com/\\2\">@\\2</a>", $tweet);

Upvotes: 1

vasanth.v
vasanth.v

Reputation: 213

Wow. I found the answer myself guys.

$tweet = preg_replace('/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '$1<a href="http://twitter.com/$2">@$2</a>', $tweet);

Thanks for your help guys.

Upvotes: 2

Paul McLean
Paul McLean

Reputation: 3550

How about something like -

(?<!\w)@[\w]+

Upvotes: 1

Related Questions