php - 如何获取字符串中值的真实类型?

标签 php variables types

我在 StackOverflow 上搜索有关将字符串转换为实际值的信息,但没有找到。 我需要一个像“gettype”这样的函数来做类似上面结果的事情,但我不能全部完成:s

gettypefromstring("1.234"); //returns (doble)1,234;
gettypefromstring("1234"); //returns (int)1234;
gettypefromstring("a"); //returns (char)a;
gettypefromstring("true"); //returns (bool)true;
gettypefromstring("khtdf"); //returns (string)"khtdf";

感谢大家:)

最佳答案

Svisstack 1+! ;)

如果有人需要,这里是函数:

function gettype_fromstring($string){
    //  (c) José Moreira - Microdual (www.microdual.com)
    return gettype(getcorrectvariable($string));
}
function getcorrectvariable($string){
    //  (c) José Moreira - Microdual (www.microdual.com)
    //      With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)

    /* FUNCTION FLOW */
    // *1. Remove unused spaces
    // *2. Check if it is empty, if yes, return blank string
    // *3. Check if it is numeric
    // *4. If numeric, this may be a integer or double, must compare this values.
    // *5. If string, try parse to bool.
    // *6. If not, this is string.

    $string=trim($string);
    if(empty($string)) return "";
    if(!preg_match("/[^0-9.]+/",$string)){
        if(preg_match("/[.]+/",$string)){
            return (double)$string;
        }else{
            return (int)$string;
        }
    }
    if($string=="true") return true;
    if($string=="false") return false;
    return (string)$string;
}

我用这个函数来判断数字 X 是否是 Y 的倍数。

例子:

$number=6;
$multipleof=2;
if(gettype($number/$multipleof)=="integer") echo "The number ".$number." is multiple of ".$multipleoff.".";

但是我工作的框架总是将输入变量作为字符串返回。

关于php - 如何获取字符串中值的真实类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2690654/

相关文章:

php - 在 Kohana PHP 框架中启用 PECL HTTP

php - Silex Routing,如何在路由变量中添加斜线?

php - 这是在 android 中下载 PDF 的正确方法吗?

variables - 函数/变量作用域(按值传递还是引用传递?)

multithreading - lua中有一种名为thread的类型。有人知道这件事吗?

php - 如何用PHP显示本地时间

c - 如何计算递增变量的总计

javascript - 使用 '===' 比较 JavaScript 中的类型时出现 Visual Studio Code 警告

haskell - 在 Haskell 中以通用方式扩充复杂数据类型

c++ - C++ 中的 "Variable ' i ' was not declared in scope "是什么?