Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - split String in Key/Value pairs

Tags:

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?

like image 517
Sebastian Hoitz Avatar asked Feb 07 '11 16:02

Sebastian Hoitz


2 Answers

If you don't mind using regex ...

$str = "key=value, key2=value2"; preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r);  $result = array_combine($r[1], $r[2]); var_dump($result); 
like image 161
etarion Avatar answered Sep 23 '22 18:09

etarion


<?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?> 
like image 43
KomarSerjio Avatar answered Sep 24 '22 18:09

KomarSerjio