Split text into lines when pattern matches in PHP

Possible duplicate:
Splitting a string array based on numbers in php?

I have a dataset that is all in one large piece of text. It looks something like this:

01/02 10:45:01 test data 01/03 11:52:09 test data 01/04 18:63:05 test data 01/04 21:12:09 test data 01/04 13:10: 07 test data 01/05 07:08:09 test data 01/05 10:07:08 test data 01/05 08:00:09 test data 01/06 11:01:09 test data

I am trying to just make it readable (see below, for example), but the only thing on each of the lines that are remotely similar is that the start follows pattern 00/00.

01/02 10:45:01 test data 01/03 11:52:09 test data 01/04 18:63:05 test data 01/04 21:12:09 test data 01/04 13:10:07 test data 01/05 07:08:09 test data 01/05 10:07:08 test data 01/05 08:00:09 test data 01/06 11:01:09 test data 

I got to its separation by matching it with a regular expression pattern;

 $split = preg_split("/\d+\\/\d+ /", $contents, -1, PREG_SPLIT_NO_EMPTY); 

And these are the exits;

 Array ( [0] => [1] => 10:45:01 test data [2] => 11:52:09 test data [3] => 18:63:05 test data [4] => 18:63:05 test data ...and so on 

But, as you can see, the problem is that preg_split does not support the delimeter. I tried changing preg_split to;

 $split = preg_split("/\d+\\/\d+ /", $contents, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE 

However, this returns the same as above, with no 00/00 at the beginning of the line.

Am I doing something wrong or is their best way to achieve this?

+4
source share
2 answers

You can tell preg_split() about a split at any point in the string followed by a slash with a lookahead assertion .

 $result = preg_split('#(?=\d+/\d+)#', $contents, -1, PREG_SPLIT_NO_EMPTY); 

The PREG_SPLIT_NO_EMPTY flag PREG_SPLIT_NO_EMPTY used, since the very beginning of the line is also the point where there are three digits, so there is an empty division. We could change the regular expression so that it does not break at the very beginning of the line, but that would make it more difficult to understand at first glance, while the flag is very clear.

+4
source

PHP:

 <?php $text = '01/02 10:45:01 test data 01/03 11:52:09 test data 01/04 18:63:05 test data 01/04 21:12:09 test data 01/04 13:10:07 test data 01/05 07:08:09 test data 01/05 10:07:08 test data 01/05 08:00:09 test data 01/06 11:01:09 test data'; $text = preg_replace('/(\d{2})\/(\d{2})(.*)/U', PHP_EOL . "$0", $text); echo $text; 

Output:

 01/02 10:45:01 test data 01/03 11:52:09 test data 01/04 18:63:05 test data 01/04 21:12:09 test data 01/04 13:10:07 test data 01/05 07:08:09 test data 01/05 10:07:08 test data 01/05 08:00:09 test data 01/06 11:01:09 test data 

Demo

+2
source

All Articles