在DB表中存储的典型值如下:
$value1 = "123,232,453";
$value2 = "123,232,453.45";
逗号和小数。我必须检测数据上传后是否有任何数据输入错误。上传过程对我来说是一个黑盒子,很可能在那里有一个数字格式。
I tried
ctype_digit($value1)
检查,但逗号没有任何帮助。
当值中有逗号时,是否有方法检查整数?
您可以通过将输入处理为字符串来简单地去掉逗号:
$value1 = str_replace(',', '', $value1);
然后可以使用正则表达式检查整数:
if (preg_match('/^-?'d+$/', $value1)) {
...
}
或者,如果允许小数,可以使用is_numeric()
if (is_numeric($value1)) {
...
}
检查逗号:
if(strpos($value, ",")){
// there is a comma
}else{
// there is no comma
}
使用更实用的样式并避免使用正则表达式,可以这样做:
$values[] = "123,232,453";
$values[] = "123,232,453.45";
$values[] = "123,232,453.45b";
$result = array_map(
function ($val) {
return array_reduce(
explode(",", $val),
function ($carry, $item) {
return $carry && filter_var($item, FILTER_VALIDATE_FLOAT) !== false;
}, true
);
}, $values
);
var_dump($result);
这将在cli上输出以下内容。最后一个元素将为false,因为最后一个测试用例包含无效的数字。
array(3) {
[0] =>
bool(true)
[1] =>
bool(true)
[2] =>
bool(false)
}
对于values
中的所有项目,它在,
爆炸项目,然后使用过滤器检查每个结果是否为有效的浮点数/数。