PHP - 清理逗号分隔的字符串
清理用户输入(完全由数字组成的逗号分隔字符串)的最有效方法是什么 - 例如
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;}
所以我应该分解它,然后用上面的代码检查数组的每个元素,或者替换所有出现的 ' ,' 和 '' 然后检查整个内容是一个数字吗?你们觉得怎么样?
What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g
2,40,23,11,55
I use this function on a lot of my inputs
function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }
And on simple integers I do:
if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}
So should I explode it and then check every element of the array with the code above or maybe replace all occurrences of ',' with '' and then check the whole thing is a number? What do you guys think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果它是 CSV 并且数字或逗号周围可能有空格,甚至可能有一些引号,最好使用正则表达式来检查它是否匹配
If it is CSV and if there might be spaces around the digits or commas and maybe even some quotation marks better use a regex to check if it matches
如果您想转换逗号分隔的列表,而不是在格式不正确时简单地拒绝它,您可以使用
array_map()
并避免编写显式循环。If you want to transform a comma-separated list instead of simply rejecting it if it's not formed correctly, you could do it with
array_map()
and avoid writing an explicit loop.我会过滤而不是对简单输入进行错误检查,尽管只是因为我很懒,我想,通常在网络环境中,有太多的情况需要处理可能出现的情况,而我没有想到:简单过滤下面。
?>
以下是键盘上的代码和输出:
http://codepad.org/YfSenm9k
I would filter instead of error checking on simple input, though only 'cause I'm lazy, I suppose, and usually in a web context there's way too many cases to handle on what could be coming in that I wouldn't expect: Simple filter below.
?>
Here's the code and the output on codepad:
http://codepad.org/YfSenm9k