2011-09-26 33 views
1

我在格式鍵的字符串的一些數據:值鍵:值鍵:值等..PHP正則表達式匹配的煩惱

我試圖把它變成使用正則表達式匹配的數組。所有的鍵都是大寫字母,後面跟着一個冒號。然後有一個空間,價值開始。然後是空格,然後是下一個鍵。該值可以包含大寫/小寫字母,數字,空格,逗號或等號。

例如,我想該輸入字符串:

NAME: Name of Item COLOR: green SIZE: 40 

化作此數組:

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

任何幫助十分讚賞。此外,我無法訪問輸入的格式,或者我會讓自己更容易。

+0

如果其中一個答案解決以下通過點擊您的問題,請接受它答案旁邊的勾號 – ghostJago

回答

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

Paul的答案對我的數據集效果更好,但感謝您的幫助。 – brack

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"; 
+0

如果我的示例被硬編碼到輸入中,那麼這樣做會很好,但是輸入會改變,我並不總是知道密鑰的數量或名稱。儘管感謝您的幫助。 – brack

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

工作就像一個魅力。謝謝你的幫助。 – brack