如何使用Regex验证Twitter用户名 [英] How to validate a Twitter username using Regex

查看:216
本文介绍了如何使用Regex验证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

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

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