preg_split与正则表达式给出错误的输出

时间:2012-11-15 09:19:08

标签: php regex preg-split

我正在使用preg_split来表示字符串,但是我没有获得所需的输出。例如

$string = 'Tachycardia limit_from:1900-01-01 limit_to:2027-08-29 numresults:10 sort:publication-date direction:descending facet-on-toc-section-id:Case Reports';
$vals = preg_split("/(\w*\d?):/", $string, NULL, PREG_SPLIT_DELIM_CAPTURE);

正在生成输出

 Array
(
    [0] => Tachycardia 
    [1] => limit_from
    [2] => 1900-01-01 
    [3] => limit_to
    [4] => 2027-08-29 
    [5] => numresults
    [6] => 10 
    [7] => sort
    [8] => publication-date 
    [9] => direction
    [10] => descending facet-on-toc-section-
    [11] => id
    [12] => Case Reports
)

哪个错了,希望输出它

Array
(
    [0] => Tachycardia 
    [1] => limit_from
    [2] => 1900-01-01 
    [3] => limit_to
    [4] => 2027-08-29 
    [5] => numresults
    [6] => 10 
    [7] => sort
    [8] => publication-date 
    [9] => direction
    [10] => descending
    [11] => facet-on-toc-section-id
    [12] => Case Reports
)

正则表达式有问题,但我无法修复它。

3 个答案:

答案 0 :(得分:5)

我会用

$vals = preg_split("/(\S+):/", $string, NULL, PREG_SPLIT_DELIM_CAPTURE);

输出完全符合您的要求

答案 1 :(得分:1)

尝试使用此正则表达式,而不是在拆分模式中包含“ - ”或其他字符:http://regexr.com?32qgs

((?:[\w\-])*\d?):

答案 2 :(得分:1)

这是因为\w类不包含字符-,所以我也会扩展\ w:

/((?:\w|-)*\d?):/