How to validate a Twitter username using Regex How to validate a Twitter username using Regex php php

How to validate a Twitter username using Regex


To validate if a string is a valid Twitter handle:

function validate_username($username){    return preg_match('/^[A-Za-z0-9_]{1,15}$/', $username);}

If you are trying to match @username within a string.

For example: RT @username: lorem ipsum @cjoudrey etc...

Use the following:

$string = 'RT @username: lorem ipsum @cjoudrey etc...';preg_match_all('/@([A-Za-z0-9_]{1,15})/', $string, $usernames);print_r($usernames);

You can use the latter with preg_replace_callback to linkify usernames in a string.

Edit: Twitter also open sourced text libraries for Java and Ruby for matching usernames, hash tags, etc.. You could probably look into the code and find the regex patterns they use.

Edit (2): Here is a PHP port of the Twitter Text Library: https://github.com/mzsanford/twitter-text-php#readme


Don't use / with ereg*.

In fact, don't use ereg* at all if you can avoid it. http://php.net/preg_match

edit: Note also that /[a-z0-9_]+/i will match on spaces are invalid and not-a-real-name. You almost certainly want /^[a-z0-9_]+$/i.

S


I believe that you're using the PCRE form, in which case you should be using the preg_match function instead.