使用 = 和 & 解析字符串 作为分隔符,但不是全部 & 是向前看的分隔符
我在 PHP 中有这个字符串:
$string = "name=Shake & Bake&difficulty=easy";
我想将其解析为数组:
Array
(
[name] => Shake & Bake
[difficulty] => easy
)
NOT:
Array
(
[name] => Shake
[difficulty] => easy
)
最有效的方法是什么?
I have this string in PHP:
$string = "name=Shake & Bake&difficulty=easy";
For which I want to parse into array:
Array
(
[name] => Shake & Bake
[difficulty] => easy
)
NOT:
Array
(
[name] => Shake
[difficulty] => easy
)
What is the most efficient way to do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可能有一种更有效的方法可以做到这一点,但请尝试
PHP 的正则表达式引擎 PCRE,它支持前瞻断言。 谷歌搜索 PCRE、PHP、RegEx、前瞻断言和零宽度断言应该会为您提供有关该主题的更多信息。
There's probably a more effective way of doing this, but try
PHP's regex engine is PCRE, and it supports look ahead assertions. Googling around for PCRE, PHP, RegEx, look ahead assertions and zero width assertions should give you more than you ever want to know on the subject.
正则表达式似乎是做到这一点的最佳方法。
输出:
Regular expressions seems to be the best way to do this.
Output:
produces
which seems to be working (except for difficulty= not being matched in the last example).
I'm not sure whether a once-only subpattern matching would improve the speed. You might want to look this up.
produces
which seems to be working (except for difficulty= not being matched in the last example).
I'm not sure whether a once-only subpattern matching would improve the speed. You might want to look this up.
函数 parse_str() 正是您所需要的 - 只是确保出于明显的安全原因传递第二个参数。 不过,您需要翻译您的输入字符串:
The function parse_str() does exactly what you need - just make sure, you pass the second parameter for obvious security reasons. You need to translate your input string, though:
urlencode() & 在“摇动和烘烤”中并使用 parse_str()
urlencode() the & in "Shake & Bake" and use parse_str()