Reputation: 109
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?
Upvotes: 0
Views: 129
Reputation: 48031
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);
Upvotes: 0
Reputation: 173652
You can use array_chunk()
:
$values = array_chunk(explode(',', $string), 2)
foreach ($values as $pair) {
list($key, $value) = $pair;
// do something
}
Upvotes: 1
Reputation: 158170
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"
}
Upvotes: 0
Reputation: 174816
You could try the below regex to get the key, value pairs.
([a-z]+),(\d+(?:\.\d+)?)
Upvotes: 2