如何获取字符串中值的真实类型? [英] How to get the real type of a value inside string?
本文介绍了如何获取字符串中值的真实类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 StackOverflow 上搜索有关将字符串转换为实际值的内容,但没有找到.我需要一个像gettype"这样的函数来做类似上面的结果,但我不能做这一切:s
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";
谢谢大家:)
推荐答案
1+ for Svisstack!;)
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;
}
我用这个函数来知道数字 X 是否是 Y 的倍数.
I used this function to know if the number X is multiple of Y.
示例:
$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.
这篇关于如何获取字符串中值的真实类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文