我认为这非常简单,但是在PHP中,要确定字符串是否仅包含 整数或浮点数(整数或半数)是很棘手的。
例如,我想要:
// Approved
"0.5"
"12"
"22.5"
"6.0"
"1"
"0"
// Rejected
"0.65"
"foo19bar"
"ten"
"39.4"
"s12"
"0x600"
棘手的事情
很难(仅)检测字符串中的浮点数:
is_float()
显然拒绝字符串(例如is_float("2.5") = false
)is_float((float)"wat2.5") = true
)确定浮点数是完整还是一半也很奇怪:
%
)由于某种原因会自动转换为int
,因此您需要使用fmod()
(例如,PHP中的10.33 % 0.5
返回0
5.4)到目前为止,我最简洁的解决方案是这个,但是我觉得应该有一个更好的方法:
if (ctype_digit($rating) || (is_float($rating + 0) && fmod($rating, 0.5) == 0)) {
if (is_numeric($rating)) {
echo "Approved";
}
}
答案 0 :(得分:2)
<?php
$test = [
"0.5",
"12",
"22.5",
"6.0",
"1",
"0",
"0.65",
"foo19bar",
"ten",
"39.4",
"s12",
"0x600",
];
foreach ($test as $number)
if ((string)((int)((double)$number * 2) / 2) == $number)
echo "Approved $number\n";
else
echo "Rejected $number\n";
输出:
Approved 0.5
Approved 12
Approved 22.5
Approved 6.0
Approved 1
Approved 0
Rejected 0.65
Rejected foo19bar
Rejected ten
Rejected 39.4
Rejected s12
Rejected 0x600
答案 1 :(得分:1)
为什么不仅仅使用正则表达式,例如
if (preg_match('/^\d+(\.[05]0*)?$/', $rating)) echo "\"$rating\": Approved\n";
此数字将允许在数字后跟0,因此4.50和4.5都会通过。如果您不希望这样做,只需删除其中的0*
部分即可。
例如
$ratings = array(
"0.5",
"12" ,
"22.5" ,
"6.0",
"1",
"0",
"4.5",
"3.500",
"1.00",
"0.65" ,
"foo19bar" ,
"ten" ,
"39.4",
"s12",
"0x600"
);
foreach ($ratings as $rating) {
echo "\"$rating\": " . (preg_match('/^\d+(\.[05]0*)?$/', $rating) ? "Approved\n" : "Rejected\n");
}
输出:
"0.5": Approved
"12": Approved
"22.5": Approved
"6.0": Approved
"1": Approved
"0": Approved
"4.5": Approved
"3.500": Approved
"1.00": Approved
"0.65": Rejected
"foo19bar": Rejected
"ten": Rejected
"39.4": Rejected
"s12": Rejected
"0x600": Rejected