2014-05-07 34 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