如何最好地检查输入是否为数字?
- 1-
- +111+
- 5xf
- 0xf
这些类型的数字不应该是有效的,只有像123、012(12)、正数这样的数字应该是有效的。 这是我的当前代码:
$num = (int) $val;
if (
preg_match('/^\d+$/', $num)
&&
strval(intval($num)) == strval($num)
)
{
return true;
}
else
{
return false;
}
如何最好地检查输入是否为数字?
这些类型的数字不应该是有效的,只有像123、012(12)、正数这样的数字应该是有效的。 这是我的当前代码:
$num = (int) $val;
if (
preg_match('/^\d+$/', $num)
&&
strval(intval($num)) == strval($num)
)
{
return true;
}
else
{
return false;
}
ctype_digit
函数正是为了这个目的而设计的。
我使用
if(is_numeric($value) && $value > 0 && $value == round($value, 0)){
验证一个值是否为数字、正数和整数
我不太喜欢ctype_digit,因为它没有"is_numeric"可读性高,并且在你确实希望验证一个值是否为数字时,它实际上有更少的缺陷。
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
ctype_digit
更好。 - user895378return ctype_digit($num) && (int) $num > 0
对于 PHP 4 版本或更高版本:
<?PHP
$input = 4;
if(is_numeric($input)){ // return **TRUE** if it is numeric
echo "The input is numeric";
}else{
echo "The input is not numeric";
}
?>
if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
//if all made of numbers "-" or ".", then yes is number;
}