cus*_*pvz 1 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";
Run Code Online (Sandbox Code Playgroud)
谢谢大家 :)
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;
}
Run Code Online (Sandbox Code Playgroud)
我用这个函数来知道数字X是否是Y的倍数.
例:
$number=6;
$multipleof=2;
if(gettype($number/$multipleof)=="integer") echo "The number ".$number." is multiple of ".$multipleoff.".";
Run Code Online (Sandbox Code Playgroud)
但是我工作的框架总是将输入变量作为字符串返回.
您必须尝试按指定顺序转换它:
您不能使用gettype,因为您可能会在字符串中获得十进制字符串的字符串类型.