PHP is_numeric or preg_match 0-9 validation

前端 未结 11 1531
别跟我提以往
别跟我提以往 2020-12-13 02:48

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_numeric

相关标签:
11条回答
  • 2020-12-13 03:13

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

    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.

    0 讨论(0)
  • 2020-12-13 03:14

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

    0 讨论(0)
  • 2020-12-13 03:14

    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:

    /^[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:

    /^[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:

    $expr = '/^[1-9][0-9]*$/';
    if (preg_match($expr, $id) && filter_var($id, FILTER_VALIDATE_INT)) {
        echo 'ok';
    } else {
        echo 'nok';
    }
    
    0 讨论(0)
  • 2020-12-13 03:15

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

    0 讨论(0)
  • 2020-12-13 03:19

    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.

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

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

    <?php
      $id = $_GET['id'];
      if (ctype_digit($id)) {
          echo 'ok';
      } else {
          echo 'nok';
      }
    ?>
    
    0 讨论(0)
提交回复
热议问题