开发者

PHP Regex Match Troubles

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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜