【问题标题】:PHP: Best way to check if input is a valid number?PHP:检查输入是否为有效数字的最佳方法?
【发布时间】:2012-07-10 05:35:59
【问题描述】:

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

  • 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;
}

【问题讨论】:

  • 不要在代码的第一行创建 (int) !将其转换为 (string) 然后使用带有 ctype_digit($num) 的字符串会比 int(proff in manual php.net/ctype_digit) 做得更好!!!

标签: php input validation numeric


【解决方案1】:

最安全的方式

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

【讨论】:

  • 这不起作用,例如 OP 的“1-”示例不应被视为有效数字,但根据这个正则表达式它是。
  • @rowatt \- 用于负数。我在乞讨时将其更改为仅考虑“-”
【解决方案2】:

对于 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";
}
?>

【讨论】:

    【解决方案3】:

    我用

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

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

    http://php.net/is_numeric

    我不太喜欢 ctype_digit,因为它的可读性不如“is_numeric”,而且当您真正想验证一个值是否为数字时,它实际上具有较少的缺陷。

    【讨论】:

    • 除了 OP 只寻找正整数,而不是数字。
    【解决方案4】:
    return ctype_digit($num) && (int) $num > 0
    

    【讨论】:

      【解决方案5】:

      filter_var()

      $options = array(
          'options' => array('min_range' => 0)
      );
      
      if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
       // you're good
      }
      

      【讨论】:

      • +1 因为这是一个比ctype_digit更语义化(虽然更冗长)的解决方案@
      【解决方案6】:

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

      【讨论】:

      • couse 在第一行 $num = (int) $val; 如果转换为字符串,$num = (string) $val;会好的,因为它是手动输入的!!!
      猜你喜欢
      • 2011-01-04
      • 2011-05-30
      • 1970-01-01
      • 2013-02-18
      • 2010-12-20
      • 2020-11-21
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      相关资源
      最近更新 更多