如果一个字符串可以转换成一个整数,如何在PHP中进行检查?
例如,“000”、“404”和“0523”可以在PHP中转换为整数,但“42sW”和“423 2343”不能转换为整数。应该是您要找的。使用如果一个字符串可以转换成一个整数,如何在PHP中进行检查?,php,Php,例如,“000”、“404”和“0523”可以在PHP中转换为整数,但“42sW”和“423 2343”不能转换为整数。应该是您要找的。使用是数字() PHP的是数值()可以确定给定参数是数字还是数字字符串。请通读一些示例 你可以试试这样的东西 <?php if (is_numeric($string)) { //functions here } else{ //functions2 here } ?> 42Sw可以使用intval()转换为数字 使用ctype\u digit功能
是数字()
PHP的是数值()
可以确定给定参数是数字还是数字字符串。请通读一些示例 你可以试试这样的东西
<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>
42Sw可以使用intval()转换为数字
使用ctype\u digit
功能<代码>是数字的
也允许浮点值
$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
}
}
}
除了检查字符串中的每个字符是否都是数字之外,您还需要其他东西吗?您在考虑吗?对于非整数(1.23)是否也会返回true?谢谢,
ctype\u digit
非常有效is_numeric
不起作用,因为所有有理数都适用于is_numeric,但是知道这个函数也很好,谢谢@格斯:你想说什么呢?如果你输入int,不管它是一个整数,它都会返回false。这可能是预料不到的。值得一提的是,干杯。$numArray=array(“1.23”、“156”、“143”、“1w”);1.23假156假143真1wfalse@DavidFaux:1.2e2是一个“整数”,但将无法通过ctype、\u digit()测试。这对于“1.5”之类的东西是正确的,对于“1.5”之类的东西是正确的,对于“1.5”之类的东西是正确的
$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
echo intval("42sW"); // prints 42
$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
}
}
}