防止用户在 PHP 中爆炸字符串

发布于 2024-10-06 12:14:22 字数 160 浏览 7 评论 0原文

我遇到的情况是,我需要分解一个包含用户输入但包含自定义分隔符的字符串。我想确保用户无法在输入中输入该分隔符,以免在错误的位置分解字符串。

最好的方法是什么?我是否应该对用户数据运行某种类型的过滤器来删除分隔符的出现?我认为有一个比仅仅创建一个唯一的分隔符更好的答案。

谢谢。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫南 2024-10-13 12:14:22

这是一个古老的问题,所以按照已经解决的方式来解决它。

在 CSV 文件中,逗号是分隔符,但条目可以包含逗号。如何?用引号将条目括起来。如果条目包含引号怎么办?将用户输入的引号加倍,这样您就知道它们是数据而不是分隔符。

Field One,Field Two,"Field, Three","Field ""Four"""

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.

Field One,Field Two,"Field, Three","Field ""Four"""

PHP has functions for creating and reading CSV format with custom-defined delimiters, so you don't even have to write the code.

红衣飘飘貌似仙 2024-10-13 12:14:22

如果您的环境中没有 str-getcsv,则按照原始问题中的评论。

假设您的分隔符是管道符号,

$clientString = 'somestring|fobar';
$clientString = str_replace('|', '{{{somecrazydelimiter}}}', $clientString);

您可以稍后在分解它后扭转情况,并将临时分隔符替换为原始分隔符:

$clientString = str_replace('{{{somecrazydelimiter}}}', '|', $clientString);

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

$clientString = 'somestring|fobar';
$clientString = str_replace('|', '{{{somecrazydelimiter}}}', $clientString);

You can the later reverse the situation after exploding it and replace your temporary delimiter with original one:

$clientString = str_replace('{{{somecrazydelimiter}}}', '|', $clientString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文