正则表达式不适用于密码?不知道为什么
所以我有一个正则表达式代码来确保密码是从 4 到 13 个字符,它一直失败
public function valid_password($password){
if(preg_match('^.{3,14}^', $password)){
return true;
}//end if
else{
return false;
}//end else
}
我使用正则表达式而不是 php 的长度属性,因为稍后我将添加更多正则表达式代码。然而,现在我被这个失败的程序困住了。
问题是,它确保密码超过 3 个字符,但它并不关心密码有多长,就好像我没有设置限制一样。
提前致谢
So I have a regex code to make sure the password is from 4 to 13 characters, it keeps failing
public function valid_password($password){
if(preg_match('^.{3,14}^', $password)){
return true;
}//end if
else{
return false;
}//end else
}
I'm using regex and not php's length attribute because I will be adding more regex code later on. However, now I'm stuck with this failing program.
The problem is, it makes sure the password is over 3 characters however it doesn't care how long it is as if I have set no limit.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您已使用
^
作为分隔符 php.net/ mregexp.reference.delimiters.php 此处:这是可能的,但在您的情况下不是一个好主意,因为您需要
^
来实现其实际目的。它通常与主题的开头匹配。为了正确计算长度,你需要这样做。您还需要主题元字符的$
结尾。所以基本上:
现在,如果您想将此正则表达式与其他匹配条件结合起来,我会推荐这种奇特的断言语法:
这将允许您指定其他内容来代替
...
- 并保持长度检查隐式。You have used
^
as delimiters php.net/mregexp.reference.delimiters.php here:That's possible, but not a good idea in your case, because you need the
^
for its actual purpose. It matches the start of the subject normally. And to correctly count the length, yout need to do that. You also need the$
end of subject meta character.So basically:
Now if you want to combine this regex with other match criteria, I would recommend this fancy assertion syntax:
This will allow you to specify something else in place of
...
- and keep the length check implicit.^
是字符串开头的锚点。字符串的末尾使用$
进行分隔:但在这种情况下,我不会使用正则表达式,而是使用
strlen
函数代替:如果您喜欢乱搞以节省该行:
但实际上,为什么要将密码长度限制为 14 个字符?这样就可以防止人们选择真正安全的密码。您可能应该提高该限制。
^
is the anchor for the beginning of a string. The end of a string is delimited using$
:But in this case I wouldn't use a regex, but the
strlen
function instead:If you like hacking around to save you that line:
But really, why do you want to restrict password length to 14 characters? That way you prevent people from choosing really secure passwords. You probably should raise that limit.
试试这个:
Try this:
尝试
使用正则表达式来计算字符串长度? = 矫枉过正
try
but regexp for counting string length?? = Overkill
^
匹配字符串的开头,而不是结尾。$
匹配结尾。而且您忘记了分隔符。
完整的固定行是:
但是,我强烈建议您改为使用:
,因为正则表达式对此完全是多余的。
^
matches the start of a string, not the end.$
matches the end.And you forgot your delimiters.
The full, fixed line is:
However, I strongly recommend that you instead use:
instead, since regular expressions are completely overkill for this.