I have a string like this:
key=value, key2=value2
and I would like to parse it into something like this:
array(
"key" => "value",
"key2" => "value2"
)
I could do something like
$parts = explode(",", $string)
$parts = array_map("trim", $parts);
foreach($parts as $currentPart)
{
list($key, $value) = explode("=", $currentPart);
$keyValues[$key] = $value;
}
But this seems ridiciulous. There must be some way to do this smarter with PHP right?
if you change your string to use
&
instead of,
as the delimiter, you can useparse_str()
If you can change the format of the string to conform to a URL query string (using
&
instead of,
, among other things, you can useparse_str
. Be sure to use the two parameter option.If you don't mind using regex ...