Instead of trying to split things, match it instead:
preg_match_all('/(\w):(\w+)/', 'b:Blue | y:Yellow | r:Red', $matches);
print_r(array_combine($matches[1], $matches[2]));
It matches an alphanumeric character, followed by a colon and then more alphanumeric characters; both parts are captured in memory groups. Finally, the first memory groups are combined with the second memory groups.
A more hacked approach is this:
parse_str(strtr('b:Blue | y:Yellow | r:Red', ':|', '=&'), $arr);
print_r(array_map('trim', $arr));
It turns the string into something that looks like application/x-www-form-urlencoded
and then parses it with parse_str()
. Afterwards, you need to trim any trailing and leading spaces from the values though.
explode()
orpreg_split()
and you needarray_combine()
. – HamZa Jul 24 '13 at 8:27