You could build the array up manually using nested explodes:
$fields = explode(',', 'Name: John, Age: 20, Phone number: 12343223');
$result = array();
foreach ($fields as $field)
{
$kvpair = explode(':', $field);
if (isset($kvpair[0]) && isset($kvpair[1]))
{
// Both key and value exist (expected case)
$result[trim($kvpair[0])] = trim($kvpair[1]);
}
else if (isset($kvpair[0]))
{
// Only the key exists. May be an error depending
// on the application, but a sensible default is
// to accept it with an empty string value.
$result[trim($kvpair[0])] = '';
}
else
{
// $field represents an empty field from the source
// string. A sensible default is to ignore it, but
// raising an error works too.
}
}
deceptikon
Challenge Accepted
3,460 posts since Jan 2012
Reputation Points: 822
Solved Threads: 474
Skill Endorsements: 57
Maybe this too:
$str = "Name: John, Age: 20, Phone number: 12343223";
$bits = preg_split("/(: )|(, )/",$str);
for($x=0;$x < count($bits)-1;$x += 2)$r[$bits[$x]] = $bits[$x + 1];
print_r($r);
Perhaps using trim would be a safe precaution too. Then you could just split on ':' and ',' without the spaces.
Not as safe as D's, as there's no checking for pairs.
diafol
Keep Smiling
10,675 posts since Oct 2006
Reputation Points: 1,632
Solved Threads: 1,514
Skill Endorsements: 57