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

med*_*414 65 php validation input numeric

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

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

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

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

小智 66

ctype_digit 是为了这个目的而建造的.


Mat*_*lin 38

我用

if(is_numeric($value) && $value > 0 && $value == round($value, 0)){
Run Code Online (Sandbox Code Playgroud)

验证值是否为数字,正数和积分

http://php.net/is_numeric

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

  • 除了OP只寻找正整数,而不是数字. (5认同)

Joh*_*nde 18

filter_var()

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

if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
 // you're good
}
Run Code Online (Sandbox Code Playgroud)

  • +1因为这是一个比`ctype_digit`更具语义性(虽然更详细)的解决方案 (5认同)

rdl*_*rey 8

return ctype_digit($num) && (int) $num > 0
Run Code Online (Sandbox Code Playgroud)


MD.*_*que 6

对于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";
}
?>
Run Code Online (Sandbox Code Playgroud)