how to check if PHP variable contains non-numbers?

2020-07-02 09:31发布

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 form fields. Thanks in advance.

9条回答
我只想做你的唯一
2楼-- · 2020-07-02 09:45

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)
查看更多
老娘就宠你
3楼-- · 2020-07-02 09:47

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.

查看更多
老娘就宠你
4楼-- · 2020-07-02 09:47

Cast and compare:

function string_contain_number($val)
{
     return ($val + 0 == $val) ? true : false;
}
查看更多
手持菜刀,她持情操
5楼-- · 2020-07-02 09:52
if(!ctype_digit($string))
    echo 'The string contains some non-digit'
查看更多
成全新的幸福
6楼-- · 2020-07-02 09:57

You can use ctype_digit

eg:

if (!ctype_digit($myString)) {
    echo "Contains non-numbers.";
}
查看更多
等我变得足够好
7楼-- · 2020-07-02 09:57

This will check whether the input value is numeric or not. Hope this helps

if(!preg_match('#[^0-9]#',$value))
{
    echo "Value is numeric";
}
else
{
    echo "Value not numeric";
}
查看更多
登录 后发表回答