Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

php - How to get the real type of a value inside string?

I was searching here on StackOverflow about converting string to the real value and i didn't found. I need a function like "gettype" that does something like the result above, but i can't do it all :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";

Thanks to all :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1+ for Svisstack! ;)

Here is the function if someone want it:

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;
}

I used this function to know if the number X is multiple of Y.

Example:

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

But the framework that i work returns always the input vars as strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...