0

我正在使用 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
)

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

4

3 回答 3

5

我会用

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

输出和你想要的完全一样

于 2012-11-15T09:29:55.383 回答
1

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

((?:[\w\-])*\d?):
于 2012-11-15T09:24:13.043 回答
1

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

/((?:\w|-)*\d?):/
于 2012-11-15T09:25:10.373 回答