PHP:检查输入是否为有效数字的最佳方法?

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

PHP: Best way to check if input is a valid number?

phpinputvalidationnumeric

提问by medusa1414

What is the best way of checking if input is numeric?

检查输入是否为数字的最佳方法是什么?

  • 1-
  • +111+
  • 5xf
  • 0xf
  • 1-
  • +111+
  • 5xf
  • 0xf

Those kind of numbers should not be valid. Only numbers like: 123, 012 (12), positive numbers should be valid. This is mye current code:

那些数字不应该是有效的。只有像:123, 012 (12) 这样的数字,正数才有效。这是我当前的代码:

$num = (int) $val;
if (
    preg_match('/^\d+$/', $num)
    &&
    strval(intval($num)) == strval($num)
    )
{
    return true;
}
else
{
    return false;
}

回答by

ctype_digitwas built precisely for this purpose.

ctype_digit正是为此目的而建造的。

回答by Mathieu Dumoulin

I use

我用

if(is_numeric($value) && $value > 0 && $value == round($value, 0)){

to validate if a value is numeric, positive and integral

验证值是否为数字、正数和整数

http://php.net/is_numeric

http://php.net/is_numeric

I don't really like ctype_digit as its not as readable as "is_numeric" and actually has less flaws when you really want to validate that a value is numeric.

我真的不喜欢 ctype_digit,因为它不像“is_numeric”那样可读,而且当你真的想验证一个值是数字时,它实际上有更少的缺陷。

回答by John Conde

filter_var()

filter_var()

$options = array(
    'options' => array('min_range' => 0)
);

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}

回答by rdlowrey

return ctype_digit($num) && (int) $num > 0

回答by MD. Shafayatul Haque

For PHP version 4 or later versions:

对于 PHP 4 或更高版本:

<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

回答by Kareem

The most secure way

最安全的方式

if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
  //if all made of numbers "-" or ".", then yes is number;
}