在命令行Php中获取输入变量的数据类型

问题描述 投票:0回答:1

这是我的代码。

$fr = fopen("php://stdin", "r");
$input = fgets($fr);


if (preg_match('/^-?[0-9]{1,4}$/', $input)) {
    echo "Integer.";
} else if (preg_match('/^[-+]?[0-9]*\.?[0-9]+$/', $input)) {
    echo "Float.";
} else if (preg_match('/[a-zA-Z\s]^[0-9]/', $input)) {
    echo "string.";
}

我将从输入的命令行中获取$input变量。我需要找到变量是int,float,string的数据类型。

尝试gettype()方法,但它总是字符串。所以只试过preg_match

虽然在这方面我也没有得到正确的输出。

例如:1.2e3我得到了字符串

php php-7 php-7.2
1个回答
0
投票

命令行(或任何管道)的所有输入将始终为字符串,因为不支持其他类型。你想弄清楚你的字符串是否是数字,然后将其转换为数字:

if (is_numeric($input)) {
    $input = +$input;
}

一元+运算符将使字符串被解释为数字,并导致intfloat

© www.soinside.com 2019 - 2024. All rights reserved.