Possible Duplicate:
Splitting string array based upon digits in php?
I have a set of data that’s all in one big chunk of text. It looks similar to the following;
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’m trying to simply make this readable (see below for example), but the only thing on each of the lines that’s remotely similar is that the start follows a 00/00 pattern.
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’ve gotten as far as splitting it out by matching it to a regex pattern;
$split = preg_split("/\d+\\/\d+ /", $contents, -1, PREG_SPLIT_NO_EMPTY);
And this outputs;
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 isn’t keeping the delimeter. I’ve tried changing the 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 start of the line.
Have I done something wrong or is their a better way of achieving this?
You can tell
preg_split()to split at any point in the string which is followed by digits-slash-digits by using a lookahead assertion.The
PREG_SPLIT_NO_EMPTYflag is used because the very start of the string is also a point where there are three digits, so an empty split happens here. We could alter the regex to not split at the very start of the string but that would make it a little more difficult to understand at-a-glance, whereas the flag is very clear.