how to check if PHP variable contains non-numbers?

前端 未结 10 2043
执笔经年
执笔经年 2021-02-18 22:09

I just want to know the method to check a PHP variable for any non-numbers and if it also detects spaces between characters? Need to make sure nothing weird gets put into my for

相关标签:
10条回答
  • 2021-02-18 22:29

    This will return true if there are non-numbers in the string. It detects letters, spaces, tabs, new lines, whatever isn't numbers.

    preg_match('#[^0-9]#',$variable)
    
    0 讨论(0)
  • 2021-02-18 22:31

    Cast and compare:

    function string_contain_number($val)
    {
         return ($val + 0 == $val) ? true : false;
    }
    
    0 讨论(0)
  • 2021-02-18 22:33

    If you mean that you only want a value to contain digits then you can use ctype_digit().

    0 讨论(0)
  • 2021-02-18 22:35

    You can use is_numeric() :

    if ( is_numeric($_POST['foo']) ) {
        $foo = $_POST['foo'];
    } else {
        // Error
    }
    

    This will check that the value is numerical, so it may contain something else than digits:

    12
    -12
    12.1
    

    But this will ensure that the value is a valid number.

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