如何使用正则表达式验证 Twitter 用户名 [英] How to validate a Twitter username using Regex

查看:84
本文介绍了如何使用正则表达式验证 Twitter 用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数中使用了模式 /[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

这篇关于如何使用正则表达式验证 Twitter 用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆