检查字符串是否为数字的最安全 php 方法是什么?

What is the safest php method to check that a string is a number?

我检查了各种方法(is_numeric,isset),但我不确定构建的方法在任何情况下都是安全的。

我需要它工作,即使要检查的变量是:

也许函数 is_numeric() 对您有用 http://php.net/manual/en/function.is-numeric.php

所有内置函数都非常安全

也许试试这个代码:

if (!empty($variable) && is_numeric($variable)) {...}

我希望这涵盖了您的所有案例。 is_numeric 看起来很安全。

$values = [
    0,
    -3232323,
    423432094823904832948234574072357589345789345789345791305432794827342365786345693453417846393,
    123232e43,
    '-1232132132',
    '023',
    'abcdefaf',
    '0xdeadbeef',
    '',
    null
];


foreach ($values as $val) {
    echo var_export($val, true);
    if (is_numeric($val))
        echo " is numeric\n";
    else
        echo " is NOT numeric\n";
}

输出:

0 is numeric
-3232323 is numeric
4.2343209482390483E+92 is numeric
1.23232E+48 is numeric
'-1232132132' is numeric
'023' is numeric
'abcdefaf' is NOT numeric
'0xdeadbeef' is NOT numeric
'' is NOT numeric
NULL is NOT numeric