简体   繁体   English

如果字符串可以转换为整数,如何检查PHP?

[英]How can one check in PHP if a string can be converted into a whole number?

例如,“000”,“404”和“0523”可以在PHP中转换为整数,但是“42sW”和“423 2343”不能转换为整数。

Use the ctype_digit function. 使用ctype_digit函数。 is_numeric will also permit floating point values. 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
        }
    }
}

PHP's is_numeric() can determine if a given param is a number or a number string . PHP的is_numeric()可确定给定的参数是一个数字或一个数字字符串 Have a read through the manual for some examples. 阅读本手册中的一些示例。

ctype_digit应该是您正在寻找的。

use is_numeric() : 使用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

42Sw可以使用intval()转换为数字

      echo intval("42sW"); // prints 42

You could try something like this. 你可以尝试这样的事情。

<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM