Jump to content

how to extract key-value pairs from string (not array)


NamemeNick

Recommended Posts

This seems like a simple problem but I'm a newbie struggling

 

What is the most efficient way to extract key-value pairs from a given string?  For instance I'd like to go from:

 

'height=6&weight=170&eyes=brown'

to

$height='6';
$weight='170';
$eyes='brown';

 

Please teach :-)

Link to comment
Share on other sites

Thanks guys! 

 

ghostdog74, it seems like your script will return an array rather than distinct variables holding strings.  Is that right?

 

What do you think of this one?  I got it from another source but it looks like gibberish to me (seems to work though)

$querystring = 'height=6&weight=170&eyes=brown';
preg_match_all("/(.*?)=(.*?)(&|$)/", $querystring, $matches);
for ($i = 0; $i < count($matches[0]); $i++) $$matches[1][$i] = $matches[2][$i];

Link to comment
Share on other sites

ghostdog74, it seems like your script will return an array rather than distinct variables holding strings.  Is that right?

yes, that's right. if you  don't need arrays, then after exploding on the "&", the array will contain 3 elements. that's all you need.

What do you think of this one?  I got it from another source but it looks like gibberish to me (seems to work though)

$querystring = 'height=6&weight=170&eyes=brown';
preg_match_all("/(.*?)=(.*?)(&|$)/", $querystring, $matches);
for ($i = 0; $i < count($matches[0]); $i++) $$matches[1][$i] = $matches[2][$i];

if you don't understand what its doing in the first place, then don't use it. regular expressions , although powerful, tends to make things look "gibberish". Even worse if you are not well trained in regex. Being more expressive in your codes will make your life easier next time, both in the area of maintenance and code troubleshooting.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.