22

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?

Sebastian Hoitz
  • 9,343
  • 13
  • 61
  • 77
  • Where does your data come from? Do you control how it is stored? Is it supposed to be a human readable (and writable) format? – Pekka Feb 07 '11 at 16:54

5 Answers5

23

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);
etarion
  • 16,935
  • 4
  • 43
  • 66
  • however... using explode and loop like in the OP example will more than likely prove to be more efficient than using regex to parse it. – CrayonViolent Feb 07 '11 at 17:06
  • 1
    You never know that before you benchmark it. It heavily depends on the usage pattern. – etarion Feb 07 '11 at 17:10
  • I just had to use this. You nailed it! – b01 Aug 15 '13 at 17:46
  • I have $selectedSoftware = array("AntiVirus ($20)","Norton ($100)"); $n = implode(',',$selectedSoftware); $bool = preg_match_all("/([^,]+) \(\$(\d+)\)/", $n, $matches); and it returns 0 can't figure out why, i tested it here http://www.phpliveregex.com/p/by8 – Aymon Fournier Jun 12 '15 at 19:43
14
<?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?>
KomarSerjio
  • 2,861
  • 1
  • 16
  • 12
11

if you change your string to use & instead of , as the delimiter, you can use parse_str()

Jed Fox
  • 2,979
  • 5
  • 28
  • 38
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
2

If you can change the format of the string to conform to a URL query string (using & instead of ,, among other things, you can use parse_str. Be sure to use the two parameter option.

Spencer Hakim
  • 1,543
  • 9
  • 19
1

Here's a single command solution using array_reduce formatted in multple lines for readability:

<?php
$str = "key=value, key2=value2";
$result = array_reduce(
   explode(',', $str), 
   function ($carry, $kvp) {
      list($key, $value)=explode('=', $kvp); 
      $carry[trim($key)]=trim($value); 
      return $carry;
    }, []);

Eli Algranti
  • 8,707
  • 2
  • 42
  • 50