0

I'm using preg_split to an string, but I'm not getting desired output. For example

$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);

is generating output

 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
)

Which is wrong, desire output it

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
)

There something wrong with regex, but I'm not able to fix it.

Sharique
  • 4,199
  • 6
  • 36
  • 54

3 Answers3

5

I would use

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

Output is exactly like you want

1

Try this regex instead to include '-' or other characters in your splitting pattern: http://regexr.com?32qgs

((?:[\w\-])*\d?):
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
1

It's because the \w class does not include the character -, so i would expand the \w with that too:

/((?:\w|-)*\d?):/
complex857
  • 20,425
  • 6
  • 51
  • 54