Take the 2-minute tour ×

I have some data in a string in the format key: value key: value key: value etc...

I'm trying to turn it into an array using a regex match. The keys are all uppercase letters directly followed by a colon. Then there is a space and the value starts. This is then followed by a space and then the next key. The value can contain upper/lowercase letters, numbers, space, comma or equals sign.

For example, I'd like this input string:

NAME: Name of Item COLOR: green SIZE: 40

Turned into this array:

newArray[NAME] = Name of Item
newArray[COLOR] = green
newArray[SIZE] = 40

Any help is much appreciated. Also I don't have access to the formatting of the input, or I'd make this a lot easier on myself.

share|improve this question
if one of the answers below solved your problem please accept it by clicking on the tick next to the answer –  ghostJago Sep 27 '11 at 16:30

3 Answers 3

up vote 0 down vote accepted

I'd suggest

$str = "NAME: Name of Item COLOR: green SIZE: 40";

preg_match_all('~([A-Z]+):(.+?)(?=[A-Z]+:|$)~', $str, $m, PREG_SET_ORDER);
foreach($m as $e)
    $result[$e[1]] = trim($e[2]);

share|improve this answer
Paul's answer worked better for my dataset, but thanks for the help. –  brack Sep 26 '11 at 9:13

A generic solution:

$str = 'NAME: Name of Item COLOR: green SIZE: 40';

$split = preg_split('/([A-Z]+):/', $str, -1,

echo 'Split Array is: ' . var_export($split, true);

$newArray = array();

// Stick the key and value together (processing two entries at a time.
for ($i = 0; $i < count($split) - 1; $i = $i + 2)
   $newArray[$split[$i]] = trim($split[$i + 1]); // Probably trim them.

echo 'New Array is: ' . var_export($newArray, true);
share|improve this answer
Worked like a charm. Thanks for your help. –  brack Sep 26 '11 at 8:53

This works:

$text = "NAME: Name of Item COLOR: green SIZE: 40";
if (preg_match('/NAME: (.+) COLOR: (.+) SIZE: (\d+)/i', $text, $matches))
    $newArray = array();
    $newArray['NAME'] = $matches[1];
    $newArray['COLOR'] = $matches[2];
    $newArray['SIZE'] = $matches[3];
    echo "No matches";
share|improve this answer
That'd work well if my example was hardcoded into the input, but however the input will change and I don't always know the number or name of the keys. Thanks for your help though. –  brack Sep 26 '11 at 16:26

Your Answer


