PHP:匹配长度的简单正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2215578/
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
PHP: Simple regular expressions to match length?
提问by oni-kun
I'm creating a registration system that needs to check the name/pass etc. with REGEX (and prefer to), what I've got so far is:
我正在创建一个注册系统,需要使用 REGEX(并且更喜欢)检查名称/通行证等,到目前为止我得到的是:
//Check so numbers aren't first, such as 00foobar
preg_match('/^(?!\d)[a-z0-9]+$/iD',$usrname);
//Just simple check
preg_match('/^[a-zA-Z0-9]+$/',$psword);
But I have to do stupid things in IF statements like:
但是我必须在 IF 语句中做一些愚蠢的事情,例如:
if strlen($psword) > 30 || if (strlen($psword) < 4) ....
if strlen($psword) > 30 || if (strlen($psword) < 4) ....
How would I impliment the length checking in my two original regular expression statements? This would make me so happy..
我将如何在我的两个原始正则表达式语句中实现长度检查?这会让我很高兴..
回答by RageZ
same but using the \w and \d for word and digits, but you might want also to include basic symbols like %!?/ ... etc...
相同但使用 \w 和 \d 表示单词和数字,但您可能还想包括基本符号,如 %!?/ ... etc...
preg_match('/^[\w\d]{4,30}$/',$psword);
the {n,v}would validate for minimum n and maximum v elements before.
之前{n,v}将验证最小 n 和最大 v 元素。
like A{2,3}would validate for AAand AAA. you can take a look therefor more references
likeA{2,3}会验证AA和AAA。你可以看看那里有更多的参考
On the same fashion if you want only to set the minimum of patern {n,}would do it. For example:
以同样的方式,如果你只想设置模式的最小值{n,}就可以了。例如:
preg_match('/^[\w\d]{4,}$/',$psword);
回答by dchakarov
I think this should do the trick:
我认为这应该可以解决问题:
preg_match('/^[a-zA-Z0-9]{4,30}$/',$psword);
preg_match('/^[a-zA-Z0-9]{4,30}$/',$psword);

