1

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.

1
  • if one of the answers below solved your problem please accept it by clicking on the tick next to the answer Commented Sep 27, 2011 at 16:30

2 Answers 2

2

A generic solution:

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

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

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

Comments

0

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

print_r($result);

1 Comment

Paul's answer worked better for my dataset, but thanks for the help.

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.