I have a date field that looks like the following:
$exampleOne = 'Sep 04-08';
$exampleTwo = 'Sep 29-Oct 01';
How can I separate them to become:
$exampleOneResult = {'Sep 04', 'Sep 08'};
$exampleTwoResult = {'Sep 29', 'Oct 01'};
I was thinking to make a loop of splitting '-' first, then splitting ' ' second, but I think that would be too resource heavy?
CodePudding user response:
Split at the dash for from and to. And then check for the second value and supply if missing.
Doing such logic is not resource heavy. Why using a regex for such a simple thing?
This example is for PHP8
$exampleOne = 'Sep 04-08';
$exampleTwo = 'Sep 29-Oct 01';
print_r(parseDateRange($exampleOne));
print_r(parseDateRange($exampleTwo));
function parseDateRange($dateRange): array {
[$from, $to] = explode('-', $dateRange);
[$month] = explode(' ', $from);
if(!str_contains($to, ' ')) {
$to = "$month $to";
}
return [$from, $to];
}
prints
Array
(
[0] => Sep 04
[1] => Sep 08
)
Array
(
[0] => Sep 29
[1] => Oct 01
)