For string:
'29 July, 2014, 30 July, 2014, 31 July, 2014'
How can I split on every second comma in the string? So that my results are:
[0] => 29 July, 2014
[1] => 30 July, 2014
[2] => 31 July, 2014
For string:
'29 July, 2014, 30 July, 2014, 31 July, 2014'
How can I split on every second comma in the string? So that my results are:
[0] => 29 July, 2014
[1] => 30 July, 2014
[2] => 31 July, 2014
Not sure if you can do it in a one-liner, but a workaround would be to split on every comma then join consecutive values.
ex:
Like this
You can split with a regular expression. For example:
returns
This works OK if all your dates have 2 digits for the day part; ie 1st July will be printed as 01 July.
The reg exp is using a lookahead, so it is saying "split on a comma, if the next four characters are [space][digit][digit][space]".
Edit - I've just improved this by allowing for one or two digits, so this next version will deal with 1 July 2014 as well as 01 July 2014:
Edit - I noticed neither my nor SlyBeaver's efforts deal with whitespace; the 2nd and 3rd dates both have leading whitespace. Here's a split solution that trims whitespace:
by shifting the problematic space into the delimiter, which is discarded.
This is not a refactored solution, but it works:
I know it's almost two years ago.
This function is reusable.
String.prototype isn't necessary to make it work.. But it's easy..
The usage in this case is:
First parameter is the split, second is how many is between each.
Result are:
Or this:
UPD: You can use this regExp to a find all matches: