PHP is_numeric 或 preg_match 0-9 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7649752/
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-26 03:05:38  来源:igfitidea点击:

PHP is_numeric or preg_match 0-9 validation

phpvalidationpreg-matchisnumeric

提问by no.

This isn't a big issue for me (as far as I'm aware), it's more of something that's interested me. But what is the main difference, if any, of using is_numericover preg_match(or vice versa) to validate user input values.

这对我来说不是什么大问题(据我所知),它更多是我感兴趣的事情。但是,使用is_numericover preg_match(反之亦然)来验证用户输入值的主要区别是什么(如果有的话)。

Example One:

示例一:

<?php
    $id = $_GET['id'];
    if (!preg_match('/^[0-9]*$/', $id)) {
        // Error
    } else {
        // Continue
    }
?>

Example Two:

示例二:

<?php
    $id = $_GET['id'];
    if (!is_numeric($id)) {
        // Error
    } else {
        // Continue
    }
?>

I assume both do exactly the same but is there any specific differences which could cause problems later somehow? Is there a "best way" or something I'm not seeing which makes them different.

我认为两者完全相同,但是否有任何特定差异可能会导致以后出现问题?是否有“最佳方式”或我没有看到的使它们不同的东西。

回答by Spudley

is_numeric()tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

is_numeric()测试一个值是否是一个数字。它不一定必须是整数 - 它可以是十进制数或科学记数法中的数字。

The preg_match()example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

preg_match()您给出的示例仅检查值是否包含零到九的数字;它们中的任意数量,以任意顺序。

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

请注意,您给出的正则表达式也不是完美的整数检查器,就​​像您编写它的方式一样。它不允许负数;它确实允许零长度字符串(即根本没有数字,这可能不应该是有效的?),并且它允许数字具有任意数量的前导零,这也可能不是预期的。

[EDIT]

[编辑]

As per your comment, a better regular expression might look like this:

根据您的评论,更好的正则表达式可能如下所示:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

这会强制第一个数字仅介于 1 和 9 之间,因此您不能有前导零。它还强制它至少有一位长,因此解决了零长度字符串问题。

You're not worried about negatives, so that's not an issue.

你不担心底片,所以这不是问题。

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

您可能想要限制数字的数量,因为就目前情况而言,它将允许太大而无法存储为整数的字符串。要限制这一点,您可以将星号更改为长度限制,如下所示:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

这将允许字符串长度在 1 到 16 位之间(即第一个数字加上 0-15 个其他数字)。随意调整花括号中的数字以满足您自己的需要。如果你想要一个固定长度的字符串,那么你只需要在大括号中指定一个数字。

Hope that helps.

希望有帮助。

回答by rap-2-h

According to http://www.php.net/manual/en/function.is-numeric.php, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.

根据http://www.php.net/manual/en/function.is-numeric.php, is_numeric 允许诸如“+0123.45e6”或“0xFF”之类的东西。我认为这不是你所期望的。

preg_match can be slow, and you can have something like 0000 or 0051.

preg_match 可能很慢,你可以有像 0000 或 0051 这样的东西。

I prefer using ctype_digit (works only with strings, it's ok with $_GET).

我更喜欢使用 ctype_digit (仅适用于字符串,$_GET 可以)。

<?php
  $id = $_GET['id'];
  if (ctype_digit($id)) {
      echo 'ok';
  } else {
      echo 'nok';
  }
?>

回答by Marc B

is_numeric() allows any form of number. so 1, 3.14159265, 2.71828e10are all "numeric", while your regex boils down to the equivalent of is_int()

is_numeric() 允许任何形式的数字。所以13.141592652.71828e10都是“数字”,而你的正则表达式归结为相当于is_int()

回答by Jacob Lee

is_numeric checks whether it is any sort of number, while your regex checks whether it is an integer, possibly with leading 0s. For an id, stored as an integer, it is quite likely that we will want to not have leading 0s. Following Spudley's answer, we can do:

is_numeric 检查它是否是任何类型的数字,而您的正则表达式检查它是否是一个整数,可能带有前导 0。对于存储为整数的 id,我们很可能不希望有前导 0。按照 Spudley 的回答,我们可以这样做:

/^[1-9][0-9]*$/

However, as Spudley notes, the resulting string may be too large to be stored as a 32-bit or 64-bit integer value. The maximum value of an signed 32-bit integer is 2,147,483,647 (10 digits), and the maximum value of an signed 64-bit integer is 9,223,372,036,854,775,807 (19 digits). However, many 10 and 19 digit integers are larger than the maximum 32-bit and 64-bit integers respectively. A simple regex-only solution would be:

但是,正如 Spudley 所指出的,结果字符串可能太大而无法存储为 32 位或 64 位整数值。有符号 32 位整数的最大值为 2,147,483,647(10 位),有符号 64 位整数的最大值为 9,223,372,036,854,775,807(19 位)。但是,许多 10 位和 19 位整数分别大于最大的 32 位和 64 位整数。一个简单的正则表达式解决方案是:

/^[1-9][0-9]{0-8}$/ 

or

或者

/^[1-9][0-9]{0-17}$/

respectively, but these "solutions" unhappily restrict each to 9 and 19 digit integers; hardly a satisfying result. A better solution might be something like:

分别,但这些“解决方案”不幸地将每个限制为 9 位和 19 位整数;很难得到令人满意的结果。更好的解决方案可能是这样的:

$expr = '/^[1-9][0-9]*$/';
if (preg_match($expr, $id) && filter_var($id, FILTER_VALIDATE_INT)) {
    echo 'ok';
} else {
    echo 'nok';
}

回答by user187291

is_numeric would accept "-0.5e+12" as a valid ID.

is_numeric 将接受“-0.5e+12”作为有效 ID。

回答by PeeHaa

Not exactly the same.

不完全一样。

From the PHP docs of is_numeric:

来自 is_numeric 的 PHP 文档:

'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

With your regex you only check for 'basic' numeric values.

使用正则表达式,您只检查“基本”数值。

Also is_numeric()should be faster.

is_numeric()应该更快。

回答by MasterCassim

is_numericchecks more:

is_numeric检查更多:

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

查找给定变量是否为数字。数字字符串由可选的符号、任意数量的数字、可选的小数部分和可选的指数部分组成。因此 +0123.45e6 是一个有效的数值。也允许使用十六进制表示法 (0xFF),但不能使用符号、十进制和指数部分。

回答by vicky mahale

You can use this code for number validation:

您可以使用此代码进行数字验证:

if (!preg_match("/^[0-9]+$/i", $phone)) {
        $errorMSG = 'Invalid Number!';
        $error    = 1;
    }

回答by Bojangles

If you're onlychecking if it's a number, is_numeric()is much muchbetter here. It's more readable and a bit quicker than regex.

如果你当它是一个号码的检查,is_numeric()很多很多更好地在这里。它比正则表达式更具可读性且速度更快。

The issue with your regex here is that it won't allow decimal values, so essentially you've just written is_int()in regex. Regular expressions should only be used when there is a non-standard data format in your input; PHP has plenty of built in validation functions, even an email validator without regex.

您的正则表达式的问题在于它不允许使用十进制值,因此基本上您只是用is_int()正则表达式编写的。正则表达式只应在输入中存在非标准数据格式时使用;PHP 有很多内置的验证函数,甚至是没有 regex电子邮件验证器

回答by mixabo

PHP's is_numericfunction allows for floats as well as integers. At the same time, the is_int function is too strict if you want to validate form data (strings only). Therefore, you had usually best use regular expressions for this.

PHP 的is_numeric函数允许浮点数和整数。同时,如果要验证表单数据(仅限字符串),is_int 函数过于严格。因此,您通常最好为此使用正则表达式。

Strictly speaking, integers are whole numbers positive and negative, and also including zero. Here is a regular expression for this:

严格来说,整数是正负整数,也包括零。这是一个正则表达式:

/^0$|^[-]?[1-9][0-9]*$/

/^0$|^[-]?[1-9][0-9]*$/

OR, if you want to allow leading zeros:

或者,如果您想允许前导零:

/^[-]?[0]|[1-9][0-9]$/

/^[-]?[0] |[1-9][0-9]$/

Note that this will allow for values such as -0000, which does not cause problems in PHP, however. (MySQL will also cast such values as 0.)

请注意,这将允许使用 -0000 之类的值,但不会在 PHP 中引起问题。(MySQL 也会将这样的值转换为 0。)

You may also want to confine the length of your integer for considerations of 32/64-bit PHP platform featuresand/or database compatibility. For instance, to limit the length of your integer to 9 digits (excluding the optional - sign), you could use:

出于32/64 位 PHP 平台功能和/或数据库兼容性的考虑,您可能还想限制整数的长度。例如,要将整数的长度限制为 9 位(不包括可选的 - 符号),您可以使用:

/^0$|^[-]?[1-9][0-9]{0,8}$/

/^0$|^[-]?[1-9][0-9]{0,8}$/