【发布时间】:2012-02-24 04:07:42
【问题描述】:
例如“000”、“404”和“0523”在PHP中可以转换为整数,但“42sw”和“423 2343”不能转换为整数。
【问题讨论】:
-
您在寻找的不仅仅是检查字符串中的每个字符是否都是数字吗?
标签: php
例如“000”、“404”和“0523”在PHP中可以转换为整数,但“42sw”和“423 2343”不能转换为整数。
【问题讨论】:
标签: php
42Sw 可以使用 intval() 转换为数字
echo intval("42sW"); // prints 42
【讨论】:
你可以试试这样的。
<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>
【讨论】:
ctype_digit 应该是您要查找的内容。
【讨论】:
使用ctype_digit 函数。 is_numeric 也将允许浮点值。
$numArray = array("1.23","156", "143", "1w");
foreach($numArray as $num)
{
if (ctype_digit($num)) {
// Your Convert logic
} else {
// Do not convert print error message
}
}
}
【讨论】:
ctype_digit 效果很好。 is_numeric 不起作用,因为所有有理数都适用于 is_numeric,但也很高兴知道该函数,谢谢!
PHP 的is_numeric() 可以确定给定参数是数字还是数字字符串。阅读manual 中的一些示例。
【讨论】:
使用is_numeric():
if (is_numeric("string")) {
echo "This can be converted to a number";
}
【讨论】:
$test = "42sW";
if (ctype_digit($test)) {
echo "The string $test consists of all digits.\n";
} else {
echo "The string $test does not consist of all digits.\n";
}
//OR
is_numeric($test); // false
【讨论】:
is_numeric() 不会对非整数 (1.23) 也返回 true 吗?