有更好的方法吗?
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.
这与检查PHP中的变量是否为整数不是重复的,因为我对整数的要求/定义与那里的不同。
if (!ctype_digit($_POST['id'])) {
// contains non numeric characters
}
注意:仅适用于string
类型。因此,您必须转换为string
常规变量:
$var = 42;
$is_digit = ctype_digit((string)$var);
另请注意:它不适用于负整数。如果需要此功能,则必须使用正则表达式。我发现这个例如:
编辑:感谢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
!参见类型比较表。
$var = 'php';
var_dump($var != (int)$var); // false
$var = '0';
var_dump($var !== (int)$var); // true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句