php 正则表达式只验证自然数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4878194/
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
Regex to validate only natural numbers?
提问by soren.qvist
I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1
, 2
, 3
, etc.) without non-digit characters.
我最近发现我一直用于验证用户输入的方法接受了一些我不太满意的值。我需要它来只接受自然数(1
,2
,3
等),而不非数字字符。
My method looks like this:
我的方法是这样的:
function is_natural($str)
{
return preg_match('/[^0-9]+$/', $str) ? false : $str;
}
So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3"
and even "2.3,2.2"
因此,如果它找到除整数自然数之外的任何其他内容,它应该返回 false。问题是,它接受像"2.3"
甚至这样的字符串"2.3,2.2"
回答by Crayon Violent
perhaps you can clarify the difference between a "number" and a "digit" ??
也许您可以澄清“数字”和“数字”之间的区别?
Anyways, you can use
无论如何,您可以使用
if (preg_match('/^[0-9]+$/', $str)) {
// contains only 0-9
} else {
// contains other stuff
}
or you can use
或者你可以使用
$str = (string) $str;
ctype_digit($str);
回答by Koraktor
The problem with /^[0-9]+$/
is that it also accepts values like 0123
.
The correct regular expression is /^[1-9][0-9]*$/
.
问题/^[0-9]+$/
在于它也接受像0123
. 正确的正则表达式是/^[1-9][0-9]*$/
.
ctype_digit()
suffers the same problem.
ctype_digit()
遇到同样的问题。
If you also need to include zero use this regex instead: /^(?:0|[1-9][0-9]*)$/
如果您还需要包含零,请改用此正则表达式: /^(?:0|[1-9][0-9]*)$/
回答by Mark Baker
Use ctype_digit()instead
使用ctype_digit()代替
回答by vytsci
I got an issue with ctype_digit when invoice numbers like "000000196" had to go through ctype_digit.
当像“000000196”这样的发票号码必须通过 ctype_digit 时,我遇到了 ctype_digit 问题。
So I have used a:
所以我使用了一个:
if (preg_match('/^[1-9][0-9]?$/', $str)) {
// only integers
} else {
// string
}