有更好的方法吗?
if( $_POST['id'] != (integer)$_POST['id'] )
echo 'not a integer';
我试过了
if( !is_int($_POST['id']) )
但是 is_int()
由于某种原因不起作用。
我的表单是这样的
<form method="post">
<input type="text" name="id">
</form>
我研究过is_int()
,好像如果
is_int('23'); // would return false (not what I want)
is_int(23); // would return true
我也试过 is_numeric()
is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)
似乎唯一的办法是: [这是一种不好的方法,不要这样做,见下面的注释]
if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false
但是有没有实现上述功能的功能呢?
澄清一下,我想要以下结果
23 // return true
'23' // return true
22.3 // return false
'23.3' // return false
注意:我刚刚发现我之前提出的解决方案将对所有字符串返回 true。 (感谢 redreggae)
$var = 'hello';
if( $var != (integer)$var )
echo 'not a integer';
// will return true! So this doesn't work either.
这不是 Checking if a variable is an integer in PHP 的副本,因为我对整数的要求/定义与那里不同。
最佳答案
试试 ctype_digit
if (!ctype_digit($_POST['id'])) {
// contains non numeric characters
}
注意:它只适用于 string
类型。因此,您必须将普通变量转换为 string
:
$var = 42;
$is_digit = ctype_digit((string)$var);
另请注意:它不适用于负整数。如果你需要这个,你将不得不使用正则表达式。我找到了 this例如:
编辑:感谢 LajosVeres,我添加了 D 修饰符。所以 123\n
无效。
if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
echo 'String is a positive or negative integer.';
}
更多:使用强制转换的简单测试将不起作用,因为 "php"== 0 是 true
而 "0"=== 0 是 false
!
见 types comparisons table为此。
$var = 'php';
var_dump($var != (int)$var); // false
$var = '0';
var_dump($var !== (int)$var); // true
关于php检查变量是否为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235746/