0

I have a string like the one below, including the parenthesis:

("string" "value" "string" "value" "string" "value" ...)

The number of quoted parts are unknown with a minimum of one pair, I would like to turn this into an associative array, my desired result is:

array('string'=>$value,'string'=>$value, 'string'=>$value)

How could I do this? Preferably, I would like to use a built-in function or a one liner or create a custom function, any help would be appreciated.

MikeGA
  • 1,262
  • 4
  • 17
  • 38

3 Answers3

2

How to use build-in functions :)

$str = '("string" "value" "string1" "value1" "string2" "value2")';

$str = preg_replace('~^\("|"\)$~', '', $str);
$ar = explode('" "', $str);
$ar = array_chunk($ar,2);
$ar = array_column($ar, 1, 0);
print_r($ar);

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
  • Your method worked great! You have introduced me to two new functions I hadn't used before, I read the documentation on these and it makes sense to me now, those functions are: array_chunk and array_column. Thanks a lot! – MikeGA Jul 30 '19 at 21:49
2
<?php

$str='("foo" "bar" "ying" "yang" "apple" "orange")';

$cols    = str_getcsv(trim($str, '()'), ' ');
$chunked = array_chunk($cols, 2);
$result  = array_column($chunked, 1, 0);

var_dump($cols, $chunked, $result);

Output:

array(6) {
    [0]=>
    string(3) "foo"
    [1]=>
    string(3) "bar"
    [2]=>
    string(4) "ying"
    [3]=>
    string(4) "yang"
    [4]=>
    string(5) "apple"
    [5]=>
    string(6) "orange"
  }
  array(3) {
    [0]=>
    array(2) {
      [0]=>
      string(3) "foo"
      [1]=>
      string(3) "bar"
    }
    [1]=>
    array(2) {
      [0]=>
      string(4) "ying"
      [1]=>
      string(4) "yang"
    }
    [2]=>
    array(2) {
      [0]=>
      string(5) "apple"
      [1]=>
      string(6) "orange"
    }
  }
  array(3) {
    ["foo"]=>
    string(3) "bar"
    ["ying"]=>
    string(4) "yang"
    ["apple"]=>
    string(6) "orange"
  }
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

One way is to match the pattern of a pair of quoted strings, then fill the result array in a callback function using the two strings from the match.

preg_replace_callback('/"([^"]+)" "([^"]+)"/', function($match) use (&$result) {
    $result[$match[1]] = $match[2];
}, $str);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80