开发者

How to validate a Twitter username using Regex

开发者 https://www.devze.com 2023-01-30 00:10 出处:网络
I have used the pattern /[a-z0-9_]+/i within the function: function validate_twitter($username) { if (eregi(\'/[a-z0-9_]+开发者_开发百科/i\', $username)) {

I have used the pattern /[a-z0-9_]+/i within the function:

function validate_twitter($username) {
 if (eregi('/[a-z0-9_]+开发者_开发百科/i', $username)) {
  return true;
 }
}

With this, I test if the input is a valid twitter username, but i'm having difficulties as it is not giving me a valid result.

Can someone help me find a solution.


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.


eregi() won't expect any / or additional toggles. Just use eregi('[a-z0-9_]+')


Your regular expression is valid, although it allows spaces FYI. (If you want to test out regular expressions I recommend: http://rubular.com/).

The first issue here is your use of eregi which is deprecated as of PHP 5.3. It is recommended that you use preg_match instead, it has the same syntax. Give that a try and see if it helps.

PHP Documentation for preg_match: http://www.php.net/manual/en/function.preg-match.php PHP Documentation for eregi: http://php.net/manual/en/function.eregi.php


Twitter user names have from 1 to 15 chars... so this could be even better with /^[a-z0-9_]{1,15}$/i.

0

精彩评论

暂无评论...
验证码 换一张
取 消