2014-05-07 36 views
0
$input = "some words go here priority: p1,p2 -rank:3 status: not delayed"; 

$pattern = "/(\S+):\s*(.*?)(?=\S+:|$)|(.*?)(?=\S+:|$)/"; 

preg_match_all($pattern, $input, $matches); 

實施例:http://regex101.com/r/yM0wO1#pcreRegex的吐出額外空數組

上述圖案最終輸出在最後一個額外的空數組。 (請參閱示例中的匹配5)
一切都是我期望的方式...

如何防止多餘的空數組?

編輯: 背景INFO

予格式化爲這樣的數據:

some words go here priority: p1,p2 -rank:3 status: not delayed 

基本上我需要檢索每個數據集對應於結腸名稱。

理想的情況下,如果我能有一個陣列結構最終使得

'' => 'some words go here' 
priority => 'p1,p2' 
-rank => 3 
status => 'not delayed' 

幾個注意事項:

keywords will not have a defining colon-word (keywords are just placed in the front) 

keywords will not always exist (might just be colon-words) 

colon-words will not always exist (might just be keywords) 

回答

1

一個更好的辦法是拆分而不是匹配它。

(?=\s\S+:) 

每個字符串將包含鍵值對或僅值,如果沒有關鍵

+0

嘛,不是很......我已經添加了一些背景資料希望能夠使我所需要的更清晰。 – kylex

+0

@kylex拆分它而不是匹配它與上面的正則表達式。 – Anirudha

+0

工作得很好,謝謝! – kylex

0

試試這個

(\S+):\s*(.*?)(?=\S+:|$)|(.*?)(?=\S+:) 
+1

增加了一些必要的背景信息這也解釋了警告 – kylex