使用 PHP 正则表达式验证用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13392842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:19:33  来源:igfitidea点击:

Using PHP regex to validate username

phpregex

提问by soycharliente

I am trying to validate a username in PHP using regex and everything I submit fails the check. I'm super new at this still.

我正在尝试使用正则表达式在 PHP 中验证用户名,但我提交的所有内容均未通过检查。我在这方面还是超级新手。

if ( !preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5-31}$/', $joinUser) )

if ( !preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5-31}$/', $joinUser) )

Rules:

规则:

  • Must start with letter
  • 6-32 characters
  • Letters and numbers only
  • 必须以字母开头
  • 6-32 个字符
  • 只限字母和数字

I've been working with this online testerand this one too. I read this threadand this threadbut wasn't able to understand much as they seems to be a little bit more complicated than mine (lookaheads? and various special characters).

我一直在使用这个在线测试仪这个测试仪。我阅读了这个线程这个线程,但无法理解太多,因为它们似乎比我的更复杂一些(前瞻?和各种特殊字符)。

After reading the first thread I linked to, it seems like I'm one of the people that doesn't quite understand how saying "letters" impacts what's thought of as acceptable, i.e. foreign characters, accented characters, etc. I'm really just looking at the English alphabet (is this ASCII?) and numbers 0-9.

在阅读我链接到的第一个线程后,似乎我是其中一个不太了解“字母”如何影响被认为可接受的内容的人,即外来字符、重音字符等。我真的只看英文字母(这是 ASCII 码吗?)和数字 0-9。

Thanks.

谢谢。

回答by stema

The only problem is, you misspelled the last quantifier.

唯一的问题是,您拼错了最后一个量词。

{5-31}has to be {5,31}

{5-31}必须 {5,31}

so your regex would be

所以你的正则表达式是

if ( !preg_match('/^[A-Za-z][A-Za-z0-9]{5,31}$/', $joinUser) )

and you can skip the {1}, but it does not hurt.

你可以跳过{1},但它不会伤害。

回答by Andrius Naru?evi?ius

Apparently all you needed to change was 5,31 from 5-31.

显然,您只需要从 5-31 更改 5,31。

Working example:

工作示例:

if (preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/', "moo123"))
{
    echo 'succeeded';
}
else
{
    echo 'failed';
}

回答by rajasaur

Try this:

尝试这个:

if ( !preg_match('/^[A-Za-z][A-Za-z0-9]{5,31}$/', $joinUser) )