开发者

regex for delimited key-value pairs in a string?

开发者 https://www.devze.com 2023-02-28 08:14 出处:网络
I have a string of key-value pairs that are delimited by a character in this format: key1=value2&key2=value2& ... &keyN=valueN

I have a string of key-value pairs that are delimited by a character in this format:

key1=value2&key2=value2& ... &keyN=valueN

Right now I'm unsafely assuming every two matches to be a key-value using this regex:

[^=&]+

Is there开发者_StackOverflow中文版 a safer way to pull these values out?


If you're using PHP, I would probably try something like this:

preg_match_all('/(?:^|&)([^=&]+)=([^=&]+)(?:&|$)/', $string, $matches);

For each match, 1 should be the key and 2 should be the value.

I can't test this where I am right now, but see if it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消