开发者

Convert a string to an associative array

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

key1="value" key2="2nd value" k开发者_运维百科ey3="3rd value"


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.


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];
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜