如何使用正则表达式验证 Twitter 用户名

2021-12-25 00:00:00 validation regex twitter php

我在函数中使用了模式 /[a-z0-9_]+/i :

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;
 }
}

通过这个,我测试输入是否是有效的 twitter 用户名,但我遇到了困难,因为它没有给我一个有效的结果.

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.

推荐答案

验证字符串是否为有效的 Twitter 句柄:

To validate if a string is a valid Twitter handle:

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

如果您尝试在字符串中匹配 @username.

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

例如:RT @username: lorem ipsum @cjoudrey etc...

使用以下内容:

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

您可以将后者与 preg_replace_callback 结合使用以链接字符串中的用户名.

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

Twitter 还开源文本库用于 Java 和Ruby 用于匹配用户名、哈希标签等.您可以查看代码并找到它们使用的正则表达式模式.

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.

编辑 (2):这是 Twitter 文本库的 PHP 端口:https://github.com/mzsanford/twitter-text-php#readme

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

相关文章