0

I've a string of key value pairs with a comma as a delimiter. I need to go through the string get the key and value and push them into an array.

I'm having an issue with writing a Regex as the value is a decimal number. An example of the string is as follows:

 value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997

Any idea how to write a correct regex?

4 Answers 4

2

You could try the below regex to get the key, value pairs.

([a-z]+),(\d+(?:\.\d+)?)

DEMO

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

Comments

1

You can use array_chunk():

$values = array_chunk(explode(',', $string), 2)

foreach ($values as $pair) {
    list($key, $value) = $pair;
    // do something
}

Comments

0

You can use the following code:

$str = 'value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997';
$parts = explode(',', $str);
$result = array();
for($i=0; $i < count($parts); $i+=2) {
    $result[$parts[$i]] = $parts[$i+1];
}

var_dump($result);

Output:

array(5) {
  ["value"]=>
  string(4) "0.23"
  ["word"]=>
  string(4) "0.42"
  ["dog"]=>
  string(19) "0.28000000000000014"
  ["cat"]=>
  string(1) "0"
  ["car"]=>
  string(18) "17.369999999999997"
}

Comments

0

More approaches:

preg_match_all() with array_combine() to build the associative array. Demo

$str = 'value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997';

preg_match_all('#([^,]+),([^,]+)#', $str, $m);
var_export(array_combine($m[1], $m[2]));

Or explode, chunk, transpose, then combine. Demo

var_export(
    array_combine(
        ...array_map(
            null,
            ...array_chunk(
                explode(',', $str),
                2
            )
        )
    )
);

Or a body-less loop with array destructuring syntax. Demo

$result = [];
foreach (
    array_chunk(explode(',', $str), 2)
    as
    [$k, $result[$k]]
);
var_export($result);

Comments

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.