Jump to content

How do you parse a key=variable response in PHP?


zamrg

Recommended Posts

I've been struggling to parse a response like key1=value1;key2=value2;key3=value3, something like getclientsdetails and a few other functions spit out.

 

It would normally be something as simple as a split but the fact that any one of these value's can contain a ; raises an issue.

Link to comment
Share on other sites

I managed to solve it.

 

I'm using the current function; which will safely convert key=value to an associative array whilst still keeping any ; within values intact.

 

private function _parse_vars($str)
{
	$results = array();

	$segments = explode(';', $str);

	$last_key = '';

	foreach ($segments as $segment)
	{
		if (preg_match('/^([a-z0-9_]+)=(.*)$/i', $segment, $matches))
		{
			$last_key = $matches[1];

			$results[$last_key] = $matches[2];
		}
		else
		{
			$results[$last_key] .=  ';' . $segment;
		}
	}

	return $results;
}

Link to comment
Share on other sites

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.   Paste as plain text instead

  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.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use & Guidelines and understand your posts will initially be pre-moderated