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

前端 未结 6 553
清酒与你
清酒与你 2020-11-30 07:13

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

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

Those kind of numbers should not be valid. Onl

相关标签:
6条回答
  • 2020-11-30 07:33

    filter_var()

    $options = array(
        'options' => array('min_range' => 0)
    );
    
    if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
     // you're good
    }
    
    0 讨论(0)
  • 2020-11-30 07:33

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 07:42

    For PHP version 4 or later versions:

    <?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";
    }
    ?>
    
    0 讨论(0)
  • 2020-11-30 07:47
    return ctype_digit($num) && (int) $num > 0
    
    0 讨论(0)
  • 2020-11-30 07:52

    ctype_digit was built precisely for this purpose.

    0 讨论(0)
  • 2020-11-30 07:52

    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

    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.

    0 讨论(0)
提交回复
热议问题