Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Regex – Exploding 2 string dates in a single string

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading