is_numeric函数给出了意想不到的结果

时间:2014-05-06 09:57:50

标签: php isnumeric

我写了以下php代码,

<?php
 $k ="123e5";
if(is_numeric($k)){
    echo "is number";
}
else{
    echo "is not a number";
}
?>

预期输出“不是数字”,因为字符串中存在e。但我得到输出“是数字”。为什么会这样?请帮我找到解决方案。

3 个答案:

答案 0 :(得分:4)

根据is_numeric的文档:

  

数字字符串由可选符号,任意数量的数字组成,   可选的小数部分和可选的指数部分。因此+ 0123.45e6   是一个有效的数值。十六进制(例如0xf4c3b00c),二进制(例如,   0b10100111001),也允许使用八进制(例如0777)表示法   没有符号,十进制和指数部分。

所以给出正确的输出。

我认为您正在寻找integer only。然后使用is_int()

答案 1 :(得分:1)

您可以使用ctype_digit()检查数字字符

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
?>

答案 2 :(得分:0)

您应该使用PHP内置的过滤功能来验证用户输入。请查看以下手册页:http://www.php.net/manual/en/book.filter.php

相关问题