gpt4 book ai didi

php - 如何检查字符串是 int,但不是 double 等?

转载 作者:IT老高 更新时间:2023-10-28 11:44:45 26 4
gpt4 key购买 nike

PHP 有一个 intval() 函数,可以将字符串转换为整数。但是,我想事先检查该字符串是否为整数,以便在错误时向用户提供有用的错误消息。 PHP 有 is_int(),但是对于像 "2" 这样的字符串返回 false。

PHP 有 is_numeric() 函数,但如果数字是 double ,它将返回 true。我想要一些对 double 返回 false,但对 int 返回 true 的东西。

例如:

my_is_int("2") == TRUE
my_is_int("2.1") == FALSE

最佳答案

如何使用ctype_digit ?

来自手册:

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>

上面的例子会输出:

The string 1820.20 does not consist of all digits.The string 10002 consists of all digits.The string wsl!12 does not consist of all digits.

This will only work if your input is always a string:

$numeric_string = '42';
$integer = 42;

ctype_digit($numeric_string); // true
ctype_digit($integer); // false

如果您的输入可能是 int 类型,则将 ctype_digitis_int 结合使用.

如果您关心负数,那么您需要检查前面的 - 的输入,如果是,请在 substr 上调用 ctype_digit的输入字符串。像这样的事情会做到这一点:

function my_is_int($input) {
if ($input[0] == '-') {
return ctype_digit(substr($input, 1));
}
return ctype_digit($input);
}

关于php - 如何检查字符串是 int,但不是 double 等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com