I have a series of event dates (variable durations) in the following formats:
- 28 April 2020
- 3 – 5 May 2020
- 3 May – 5 June 2020
- 20 Dec 2020 – 15 Jan 2021
I want to keep these this way, for readability.
But my calendar needs a standard way of reading these so it can output these events:
- 28 April 2020 should become 28 April 2020 – 28 April 2020
- 3 – 5 May 2020 should become 3 May 2020 – 5 May 2020
- 3 May – 5 June 2020 should become 3 May 2020 – 5 June 2020
- 20 Dec 2020 – 15 Jan 2021 ==> this the calendar can handle.
Any thoughts on how to do this in php?
Advertisement
Answer
I would really recommend storing your dates as two separate values (start/end) and then formatting on output rather than trying to decode the formatted output.
If you are stuck with this approach, you can use preg_match
to match your different formats and then extract the start and end dates from the matched values:
$dates = array( '28 April 2020', '3 - 5 May 2020', '3 May - 5 June 2020', '20 Dec 2020 - 15 Jan 2021' ); foreach ($dates as $date) { preg_match('/^(d+)s(w+)s(d+)(?:s-s(d+)s(w+)s(d+))?|(d+)s(w+)s-s(d+)s(w+)s(d+)|(d+)s-s(d+)s(w+)s(d+)$/', $date, $matches); if (isset($matches[12])) { // dd - dd mmm yyyy format $start_date = "${matches[12]} ${matches[14]} ${matches[15]}"; $end_date = "${matches[13]} ${matches[14]} ${matches[15]}"; } elseif (isset($matches[7])) { // dd mmm - dd mmm yyyy format $start_date = "${matches[7]} ${matches[8]} ${matches[11]}"; $end_date = "${matches[9]} ${matches[10]} ${matches[11]}"; } elseif (isset($matches[4])) { // dd mmm yyyy - dd mmm yyyy format $start_date = "${matches[1]} ${matches[2]} ${matches[3]}"; $end_date = "${matches[4]} ${matches[5]} ${matches[6]}"; } elseif (isset($matches[1])) { // dd mmm yyyy format $start_date = "${matches[1]} ${matches[2]} ${matches[3]}"; $end_date = "${matches[1]} ${matches[2]} ${matches[3]}"; } else { // no match $start_date = '???'; $end_date = '???'; } echo "$start_date - $end_daten"; }
Output:
28 April 2020 - 28 April 2020 3 May 2020 - 5 May 2020 3 May 2020 - 5 June 2020 20 Dec 2020 - 15 Jan 2021