防止用户在 PHP 中爆炸字符串
我遇到的情况是,我需要分解一个包含用户输入但包含自定义分隔符的字符串。我想确保用户无法在输入中输入该分隔符,以免在错误的位置分解字符串。
最好的方法是什么?我是否应该对用户数据运行某种类型的过滤器来删除分隔符的出现?我认为有一个比仅仅创建一个唯一的分隔符更好的答案。
谢谢。
I'm in a situation where I need to explode a string which contains user input but a custom defined delimiter. I want to make sure the user cannot enter that delimiter in their input, so as not to explode the string in the wrong spot.
What is the best way to do this? Is there some type of filter I should run over the user data removing the occurrences of the delimiter? I'd think there would be a better answer than just creating a unique delimiter.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个古老的问题,所以按照已经解决的方式来解决它。
在 CSV 文件中,逗号是分隔符,但条目可以包含逗号。如何?用引号将条目括起来。如果条目包含引号怎么办?将用户输入的引号加倍,这样您就知道它们是数据而不是分隔符。
PHP 具有使用自定义分隔符创建和读取 CSV 格式的函数,因此您甚至无需编写代码。
This is an ancient problem, so solve it the way it's already been solved.
In CSV files, the comma is the delimiter, yet entries can contain commas. How? Surround the entries with quotes. What if the entry contains quotes? Double up the quotes on the user input so you know they're data and not delimiters.
PHP has functions for creating and reading CSV format with custom-defined delimiters, so you don't even have to write the code.
如果您的环境中没有 str-getcsv,则按照原始问题中的评论。
假设您的分隔符是管道符号,
您可以稍后在分解它后扭转情况,并将临时分隔符替换为原始分隔符:
If you don't have str-getcsv in your environment, then as per the comments in your original question.
Assume your delimiter is the pipe symbol
You can the later reverse the situation after exploding it and replace your temporary delimiter with original one: