1

I have a string that looks like:

KEY1,"Value"KEY2,"Value"Key3,"Value"

This string will always vary in the number of keys/values i need an associative array:

array (
    'KEY1' => 'Value',
    'KEY2' => 'Value',
    'KEY3' => 'Value'
);

of the data contained in the string, a regular expression would be best I suppose?

3 Answers 3

2

Assuming your values don't contain a " in them you can do:

$str    = 'KEY1,"Value1"KEY2,"Value2"Key3,"Value3"';
$pieces = preg_split('/(?<=[^,]")/',$str,-1,PREG_SPLIT_NO_EMPTY);
$result = array();

foreach($pieces as $piece) {
        list($k,$v) = explode(",",trim$piece);
        $result[$k] = trim($v,'"');
}

See it in action!

Sign up to request clarification or add additional context in comments.

Comments

1
php> $str = 'KEY1,"Value"KEY2,"Value"Key3,"Value"';

php> $hash = array();

php> preg_match_all("/(.*?),\"(.*?)\"/", $str, $m);

php> foreach($m[1] as $index => $key) {
 ... $hash[$key] = $m[2][$index];
 ... }

php> var_dump($hash);
array(3) {
  ["KEY1"]=>
  string(5) "Value"
  ["KEY2"]=>
  string(5) "Value"
  ["Key3"]=>
  string(5) "Value"
}

Comments

0

If the key changes between values then you'll need preg_split(). If the key is always the same then explode() should be more than adequate.

1 Comment

Explode won't work, I will need a regular expression to find what comes before the , as the key and what is inside the "" as the value. I am just no good with regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.