PHP正则表达式匹配麻烦

时间:2011-09-26 05:57:15

标签: php regex

我在字符串中有一些数据格式为key:value key:value key:value etc ...

我正在尝试使用正则表达式匹配将其转换为数组。键都是大写字母,后面跟冒号。然后有一个空格,值开始。然后是空格,然后是下一个键。该值可以包含大写/小写字母,数字,空格,逗号或等号。

例如,我想要这个输入字符串:

NAME: Name of Item COLOR: green SIZE: 40

变成了这个数组:

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

非常感谢任何帮助。此外,我无法访问输入的格式,或者我会让自己更轻松。

3 个答案:

答案 0 :(得分:2)

通用解决方案:

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

答案 1 :(得分:0)

这有效:

$text = "NAME: Name of Item COLOR: green SIZE: 40";
if (preg_match('/NAME: (.+) COLOR: (.+) SIZE: (\d+)/i', $text, $matches))
{
    //var_dump($matches);
    $newArray = array();
    $newArray['NAME'] = $matches[1];
    $newArray['COLOR'] = $matches[2];
    $newArray['SIZE'] = $matches[3];
    var_dump($newArray);
}
else
    echo "No matches";

答案 2 :(得分:0)

我建议

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