[英]unable to determine if a string is currently an integer or not
以下功能使我发疯。 地球上的100x如何等于100,然后将100x报告为整数?
对于我的一生,我无法弄清楚。 您可以复制并粘贴整个内容,然后自己查看。
我在这里某处缺少一个简单的要点,请大家帮帮我。
function blp_int($val) {
$orgval = $val;
$num = (int)$val;
echo "<li><font color=red>val: ". $val . " is being checked to see if it's an integer or not";
echo "<li><font color=red>orgval: ". $orgval ;
echo "<li><font color=red>num: ". $num ;
if ($orgval==$num) {
echo "<li><font color=red><b>YES IT IS! the [{$orgval}] is equal to [{$num}]</b>";
return true;
}
return false;
}
if (blp_int("100"))
{
echo "<h1>100 is an integer!</h1>";
}
else
{
echo "<h1>100 is NOT an integer!</h1>";
}
if (blp_int("100x"))
{
echo "<h1>100x is an integer!</h1>";
}
else
{
echo "<h1>100x is NOT an integer!</h1>";
}
上面的代码,运行时返回以下内容;
val: 100 is being checked to see if it's an integer or not
orgval: 100
num: 100
YES IT IS. the [100] is equal to [100]
100 is an integer!
val: 100x is being checked to see if it's an integer or not
orgval: 100x
num: 100
YES IT IS. the [100x] is equal to [100]
100x is an integer!
我可以通过添加以下内容来纠正这种情况
if (!is_numeric($val))
{
return false;
}
马上就到了blp_int函数的顶部,但是,..我仍然非常想知道为什么地球上php认为100x = 100是相等的。
如本例所示 ,将100x
转换为整数会将其转换为100
。 由于未使用严格比较 ,因此'100x' == 100
为true。 PHP从中删除x
,得到100
。
您可以使用严格比较(也可以比较类型),这样'100x' === 100
将返回false。 使用它,每当将字符串与整数进行比较时,它将返回false。
根据您的编辑: is_numeric
可能不是最可靠的,因为它将对格式化为字符串的数字(例如'100'
返回true。 如果希望数字为整数 (而不是字符串),则可以使用is_integer
。 我不太确定您到底在做什么,但我想我要添加此注释。
您要做什么支票? 有几种方法可以解决:
if (preg_match('!^[0-9]+$!', $input))
if (intval($input) == $input)
if (intval($input) === $input)
if ('x'.intval($input) === 'x'.$input)
这取决于您要检查它是否为整数的紧密程度。 是否需要首先trim()
它有关系吗?
可以将其强制转换为int
或尝试http://php.net/manual/en/function.ctype-digit.php 。 如果还需要===
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.