解析格式不正确的 URL 查询字符串,其中重复键缺少 []
我的字符串类似于以下格式:
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
我想像下面这样分割字符串:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
如何在 PHP 中执行此操作?
My string is like the following format:
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
How can I do this in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
$matches
现在是一个包含您想要的字符串的数组。更新
Try this:
$matches
is now an array with the strings you wanted.Update
结果将在 $strings 中
The results will be in $strings
我建议使用更简单的术语
这是一个例子
I will suggest using much simpler term
Here is an example
对此格式错误的查询字符串进行的任何手术都可能会损坏数据。
如果您知道输入的键名称或值中不会包含
=
,那么您可以通过在每个键之间注入[]
来更正查询字符串键名和等号,然后正常解析它并根据需要进行转置。代码:(Demo)
输出:
如果这还不够严格,您可以收紧替换流程以显式提名
name
和id
键。理想情况下,如果您可以控制生成此提交负载的表单字段,则最应该简单地添加
[]
字段的name
属性(
和name
)。 input type="text" name="name[]">) 或以其他方式更正该过程这会在有效负载中造成关键冲突。
Any surgery conducted on this malformed querystring may potentially corrupt data.
If you know that the input will not have
=
in the key name or values, then you can correct the querystring by injecting[]
between each key name and the equals sign, then parse it normally and transpose if you wish.Code: (Demo)
Output:
If this isn't strict enough, you can tighten the replacement process to explicitly nominate
name
andid
keys.Ideally, if you have control of the form fields which are producing this submission payload, you should most simply add
[]
the the fields'name
attributes (<input type="text" name="name[]">
and<input type="text" name="id[]">
) or otherwise correct the process that is creating key collisions in the payload.如果你想做你要求的事情,不多不少,那就是explode('&', $string)。
如果你的例子搞砸了,并且你有一个 HTTP 查询字符串,那么你想看看 parse_str()。
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().