Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split combined string

Tags:

php

I have a string which looks like this:

21/04/2014,16:57:28,19,0,2021/04/2014,16:57:48,19,0,20

I would like to split it so that I get something like the following:

21/04/2014,16:57:28,19,0,20
21/04/2014,16:57:48,19,0,20

I have tried using php's substr which I thought was giving results but it duplicated this '21/04/2014,16:57:48,19,0,20' twice.

$data3 = array(substr($data1, -27), substr($data1, 27));

Even tried a regex with no luck.

like image 583
user2011139 Avatar asked Sep 28 '26 08:09

user2011139


2 Answers

If length of parts you want to get is constant you can use str_split function with second parameter.

$data = str_split($string, 27);
like image 78
Elon Than Avatar answered Sep 30 '26 22:09

Elon Than


Elon Than's answer is the perfect solution if, as he states, the length is constant. However, I just thought I'd add this solution in case (for example) the '19' could also be '3' (or whatever):

preg_match_all("/\d{2}\/\d{2}\/\d{4}\,\d{2}:\d{2}:\d{2},\d{1,2},\d{1},\d{2}/", $string, $matches);

var_dump($matches[0]);

Notice the \d{1,2} will include any number that is 1 or 2 digits.

like image 42
rwacarter Avatar answered Sep 30 '26 23:09

rwacarter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!