PHP - 清理逗号分隔的字符串

3

如何高效地清理用户输入的逗号分隔的纯数字字符串,例如

2,40,23,11,55

我在许多输入上使用此函数。

function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }

我可以处理简单的整数操作:

if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}

那么我应该用上面的代码爆炸数组中的每个元素来检查,还是将所有出现的','替换为'',然后检查整个内容是否是一个数字?你们觉得呢?

两个答案都很好,谢谢。我测试了一下,而 jitter 的回答更有效率,大约是另一个的4倍。给你们都点赞。 - Mark
4个回答

3
if (ctype_digit(str_replace(",", "", $input))) {
  //all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
  //not ok
}

如果是CSV格式,数字或逗号周围可能会有空格,甚至可能会有引号,最好使用正则表达式来检查是否匹配。


您可能还想删除空格 - 这取决于您正在处理的“csv”文件。 - micahwittman
谢谢,我没有注意到CSV标签。 - jitter

2
if (!preg_match('/\A\d+(,\d+)*\z/', $input)) die('bad input');

0
如果您想转换以逗号分隔的列表而不仅仅是在格式不正确时拒绝它,您可以使用array_map()来完成,并避免编写显式循环。
$sanitized_input = implode(",", array_map("intval", explode(",", $input)));

我本来要同意个人不必麻烦地进行错误检查,直接进行过滤即可,但是我注意到你的代码在两个逗号并排时会插入零。 - Kzqai

0

对于简单的输入,我会使用过滤器而不是错误检查,虽然这只是因为我比较懒,我想,在 Web 上下文中,可能会出现太多意料之外的情况需要处理:以下是简单的过滤器。

<?php
$input = '234kljsalkdfj234a,a, asldkfja 345345sd,f jasld,f234l2342323@#$@#';
function clean($dirty){ // Essentially allows numbers and commas, just strips everything else.
    return preg_replace('/[^0-9,]/', "", (string) $dirty);
}

$clean = clean($input);

echo $clean;
// Result: 234234,,345345,,2342342323
// Note how it doesn't deal with adjacent filtered-to-empty commas, though you could handle those in the explode.  *shrugs*

?>

以下是代码和在codepad上的输出:

http://codepad.org/YfSenm9k


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接