2012-11-15 95 views
0

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

有什麼不對正則表達式,但我不能修復它。

回答

5

我會用

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

輸出完全像你想要的

+0

簡單而好看 – Baba

1

這是因爲\w類不包含字符-,所以我會擴大\ W與太:

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