我写了以下php代码,
<?php
$k ="123e5";
if(is_numeric($k)){
echo "is number";
}
else{
echo "is not a number";
}
?>
预期的输出是 “不是数字”,因为字符串中存在 e。但我得到了输出"is number"。为什么会这样?请帮助我找到解决方案。
as per doc of is_numeric:
Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.
so it is given right output.
I think you are looking for integer only. use is_int()
then.
You can use ctype_digit() to check for numeric character(s)
http://www.php.net/manual/en/function.ctype-digit.php
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
您应该使用 PHP 的内置过滤器函数来验证用户输入。请查看以下手册页面:http ://www.php.net/manual/en/book.filter.php