如何检查PHP变量是否包含非数字


how to check if PHP variable contains non-numbers?

我只想知道检查PHP变量是否有非数字的方法,以及它是否也检测到字符之间的空格?需要确保没有任何奇怪的东西被放入我的表单字段。提前谢谢。

如果您的意思是只希望一个值包含数字,那么您可以使用ctype_digit()

您可以使用is_numeric():

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

这将检查该值是否为数字,因此它可能包含数字以外的内容:

12
-12
12.1

但这将确保该值是有效数字

您可以使用ctype_digit

例如:

if (!ctype_digit($myString)) {
    echo "Contains non-numbers.";
}

如果字符串中有非数字,则返回true。它可以检测字母、空格、制表符、新行,以及任何不是数字的东西。

preg_match('#[^0-9]#',$variable)

这将检查输入值是否为数字。希望这能帮助

if(!preg_match('#[^0-9]#',$value))
{
    echo "Value is numeric";
}
else
{
    echo "Value not numeric";
}

对于我的测试用例,这比preg_match快了大约30%,同时仍然可以让你匹配任何你想要的字符:

if( $a !== '' && trim($a, ' 1234567890.,') === '' ){
   print("The variable contains only digits, decimal separators and spaces");
}

这只是删除字符串中提供的所有字符。如果结果是一个空字符串,那么您知道它只包含这些字符。

PHP有一个函数is_numeric(),这可能就是您想要的。

投射和比较:

function string_contain_number($val)
{
     return ($val + 0 == $val) ? true : false;
}

假设你只想要(并且只想要)有效的整数,并且你不希望用户用hexadecimalbinary或任何其他形式的数字扰乱你的数据和数据库,那么你总是可以使用这种方法:

if(((string) (int) $stringVariable) === $stringVariable) {
    // Thats a valid integer :p
}
else {
    // you are out of luck :(
}

诀窍很简单。它将字符串类型的变量强制转换为整数类型,然后再将其强制转换回字符串。超级快,超级简单。

为了测试,我准备了一个测试:

'1337' is pure integer.
'0x539' is not.
'02471' is not.
'0000343' is not.
'0b10100111001' is not.
'1337e0' is not.
'not numeric' is not.
'not numeric 23' is not.
'9.1' is not.
'+655' is not.
'-586' is pure integer.

这个方法唯一不足的地方是负数,所以你需要在旁边检查(使用((string) (int) $stringVariable) === $stringVariable && $stringVariable[0] !== "-")。

现在我认为preg_match方法是最好的。但在任何与用户打交道的项目中,速度都是一个重要因素。所以我准备了一个基准测试,做了50万次以上的测试,结果非常惊人:

我自己发明的方法只花了:
6.4700090885162
preg_match相比,完成时间为秒:
77.020107984543秒完成此测试!