验证用户名是否为带下划线的字母数字 [英] Validate username as alphanumeric with underscores

查看:235
本文介绍了验证用户名是否为带下划线的字母数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的注册页面上,我需要仅将用户名验证为字母数字,还需要带有可选的下划线.我想出了这个:

On my registration page I need to validate the usernames as alphanumeric only, but also with optional underscores. I've come up with this:

function validate_alphanumeric_underscore($str) 
{
    return preg_match('/^\w+$/',$str);
}

哪个看起来还可以,但是我不是正则表达式专家!有人发现任何问题吗?

Which seems to work okay, but I'm not a regex expert! Does anyone spot any problem?

推荐答案

实际的

The actual matched characters of \w depend on the locale that is being used:

单词"字符是任何字母或数字或下划线字符,即可以成为Perl" 单词 "的一部分的任何字符.字母和数字的定义由PCRE的字符表控制,如果进行特定于语言环境的匹配,则可能会有所不同.例如,在"fr"(法语)语言环境中,某些大于128的字符代码用于带重音的字母,并且这些字符由\ w匹配.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

因此,您最好明确指定要允许的字符:

So you should better explicitly specify what characters you want to allow:

/^[A-Za-z0-9_]+$/

这仅允许使用字母数字字符和下划线.

This allows just alphanumeric characters and the underscore.

如果您只想将下划线用作连接字符,并且要强制用户名必须以字母字符开头:

And if you want to allow underscore only as concatenation character and want to force that the username must start with a alphabet character:

/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/

这篇关于验证用户名是否为带下划线的字母数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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