0

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 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?

3 Answers 3

4

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
)
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to do this with regex:

$string = "id1:234,id3:23443,id32:andson";
preg_match_all("/([^,: ]+)\:([^,: ]+)/", $string, $res); 
$array = array_combine($res[1], $res[2]);

Comments

2

Option 1:

$string = 'id1:234,id3:23443,id32:andson';
preg_match_all('/([^,:]+)\:([^,:]+)/', $string, $matches);
$result = array_combine($matches[1], $matches[2]);

Option 2:

$string = 'id1:234,id3:23443,id32:andson';
parse_str(str_replace([':', ','], ['=', '&'], $string), $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.