PHP:preg_match 长度限制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19422589/
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: preg_match length limit
提问by Treps
I use preg_match('/[a-z]+[0-9]/', strtolower($_POST['value']))
for check that the string contains both letters and numbers. How can I change so it just allow 5 ~ 15 characters?
我preg_match('/[a-z]+[0-9]/', strtolower($_POST['value']))
用于检查字符串是否包含字母和数字。我怎样才能改变它只允许 5 ~ 15 个字符?
/[a-z]+[0-9]{5,15}/
doesn't work.
/[a-z]+[0-9]{5,15}/
不起作用。
UPDATENow I tried:
更新现在我试过:
if(preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']))) {
echo 'Valid!';
}
else {
echo 'NOOOOO!!!';
}
If I type "dfgdfgdfg" in the input field it will say "Valid!". The value has to have both letters and numbers, and between 5-15 characters.
如果我在输入字段中输入“dfgdfgdfg”,它会显示“有效!”。该值必须同时包含字母和数字,并且介于 5-15 个字符之间。
回答by HamZa
The trick is to use a positive lookahead, well in this case you'll need two.
诀窍是使用积极的前瞻,在这种情况下,您将需要两个。
So (?=.*[0-9])
will check if there is at least a digit in your input. What's next? You guessed it, we'll just add (?=.*[a-z])
. Now let's merge it with anubhava's answer:
因此(?=.*[0-9])
将检查您的输入中是否至少有一个数字。下一步是什么?你猜对了,我们只需添加(?=.*[a-z])
. 现在让我们将其与anubhava的回答合并:
(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$
What does this mean in general?
这通常意味着什么?
(?=.*[0-9])
: check if there is a digit(?=.*[a-z])
: check if there is a letter^
: match begin of string[a-z0-9]{5,15}
: match digits & letters 5 to 15 times$
: match end of string
(?=.*[0-9])
: 检查是否有数字(?=.*[a-z])
: 检查是否有字母^
: 匹配字符串的开头[a-z0-9]{5,15}
: 匹配数字和字母 5 到 15 次$
: 匹配字符串结尾
From the PHP point of view, you should always check if a variable is set:
从 PHP 的角度来看,您应该始终检查是否设置了变量:
$input = isset($_POST['value']) ? strtolower($_POST['value']) : ''; // Check if $_POST['value'] is set, otherwise assign empty string to $input
if(preg_match('~(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$~', $input)){
echo 'Valid!';
}else{
echo 'NOOOOO!!!';
}
回答by anubhava
Use line start and line end anchors with correct character class in your regex:
在正则表达式中使用具有正确字符类的行开始和行结束锚点:
preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']));
Your regex: /[a-z]+[0-9]/
will actually match 1 or more English letters and then a single digit.
您的正则表达式:/[a-z]+[0-9]/
实际上会匹配 1 个或多个英文字母,然后匹配一个数字。
回答by Prasanth Bendra
try this :
尝试这个 :
<?php
$str = your string here
preg_match('/^[a-z0-9]{5,15}$/', $str);
?>