Last Updated: February 25, 2016
·
742
· rayfranco

Catch @ Twitter usernames

/(^|[^@\w])@(\w{1,15})\b/

This allow you guys to capture twitter username in a string. This will catch words starting with @ of course, followed by 1 to 15 alphanumeric character (wich is Twitter convention for usernames). This regex will catch any twitter username, starting or ending a string, or place in the string. It will not catch email adresses ;)

I use this in a PHP function :

function twitterize($string) {
    $pattern = '/(^|[^@\w])@(\w{1,15})\b/i';
    $url_pattern = '$1<a href="http://www.twitter.com/$2">@$2</a>';
    return trim(preg_replace($pattern, $url_pattern, $string));
}

Hope you'll enjoy it !