简体   繁体   中英

Convert a string to an associative array

您如何将这样的字符串转换为PHP中的关联数组?

key1="value" key2="2nd value" key3="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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM