I have a info which is stored in a string like:
id1:234,id3:23443,id32:andson
I want to split the string with one regex but so that i get the pairs split to like in an array
array(id1=>234, id3=>s3443...)
Is there a way to do that?
I have a info which is stored in a string like:
id1:234,id3:23443,id32:andson
I want to split the string with one regex but so that i get the pairs split to like in an array
array(id1=>234, id3=>s3443...)
Is there a way to do that?
You could simply make use of array_functions. Explode the array first using , and that array will be passed as an argument to the array_map , the elements will then be passed to the user-defined function and does an inner-explode and those values are mapped as the key-value pair for the new array.
One-liner
<?php
$str='id1:234,id3:23443,id32:andson';
array_map(function ($val) use (&$valarr){ $val=explode(':',$val); $valarr[$val[0]]=$val[1];},explode(',',$str));
print_r($valarr);
Using a readable-foreach
<?php
$str='id1:234,id3:23443,id32:andson';
$arr=explode(',',$str);
foreach($arr as &$val)
{
$val=explode(':',$val);
$valarr[$val[0]]=$val[1];
}
print_r($valarr);
OUTPUT :
Array
(
[id1] => 234
[id3] => 23443
[id32] => andson
)