Sangoku
Sangoku

Reputation: 1606

PHP regular expression split with keys and values

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?

Upvotes: 0

Views: 75

Answers (3)

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
)

Upvotes: 4

Alma Do
Alma Do

Reputation: 37365

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);

Upvotes: 2

MSadura
MSadura

Reputation: 1042

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]);

Upvotes: 3

Related Questions