问题描述
在我的注册页面上,我需要仅将用户名验证为字母数字,还需要带有可选的下划线.我想出了这个:
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?
推荐答案
实际的 \w
的匹配字符取决于所使用的语言环境:
The actual matched characters of \w
depend on the locale that is being used:
因此,您最好明确指定要允许的字符:
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]+)*$/
这篇关于验证用户名是否为带下划线的字母数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!