views:

99

answers:

3

How would you convert a string like that to an associative array in PHP?

key1="value" key2="2nd value" key3="3rd value"
+4  A: 

You could use a regular expression to get the key/value pairs:

preg_match_all('/(\w+)="([^"]*)"/', $str, $matches);

But this would just get the complete key/value pairs. Invalid input like key=value" would not get recognized. A parser would do better.

Gumbo
+1  A: 

EDIT: Gumbo's answer is a better solution to this.

This any good to you?

Assume your string is in a variable like this:

$string = 'key1="value" key2="2nd value" key3="3rd value"';

First:

$array = explode('" ', $string);

you now have

array(0 => 'key1="value', 1=>'key2="2nd value', 2=>'key3="3rd value');

Then:

$result = array();
foreach ($array as $chunk) {
  $chunk = explode('="', $chunk);
  $result[$chunk[0]] = $chunk[1];
}
benlumley
having written this, I prefer gumbo's answer!
benlumley
What about `key=" value"` or `key="="`?
Gumbo
totally - as I said, prefer yours!
benlumley
+1  A: 

Using the regular expression suggested by Gumbo I came up with the following for converting the given string to an associative array:

$s = 'key1="value" key2="2nd value" key3="3rd value"';
$n = preg_match_all('/(\w+)="([^"]*)"/', $s, $matches);

for($i=0; $i<$n; $i++)
{
    $params[$matches[1][$i]] = $matches[2][$i];
}

I was wondering if you had any comments.

Emanuil
Consider accepting Gumbo's answer.
Fredrik