PHP is_numeric or preg_match 0-9 validation

前端 未结 11 1571
别跟我提以往
别跟我提以往 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: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';
    }
    

提交回复
热议问题