John Cart
John Cart

Reputation: 69

How to reformat "d-m-Y - d-m-Y" string to "Y-m-d Y-m-d"?

I want to change the format of a string containing two d-m-Y date strings separated by space hyphen space (representing a range). The desired output should have a format of Y-m-d - Y-m-d.

I can successfully execute a similar technique with d/m/Y - d/m/Y strings, but something isn't right when I am parsing the format of these new strings.

My code:

$date = "25-05-2020 - 30-05-2020";

$string = explode('-', $date);
$date1 = explode('-', $string[0]);
$date2 = explode('-', $string[1]);

$date1 = $date1[2] . '-' . $date1[0] . '-' . $date1[1];
$date2 = $date2[2] . '-' . $date2[0] . '-' . $date2[1];

echo $date1 . ' - ' . $date2;

My desired output from the sample input is 2020-05-25 - 2020-05-30.

Upvotes: 0

Views: 80

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

I find the most direct technique to be a single preg_replace() call that swaps the day and year values for each date in the string. In doing so, there is no need to generate any temporary arrays to convert the input string into the output string.

  • capture: day number ($1)
  • capture: hyphen, month number, hyphen ($2)
  • capture: year number ($3)
  • match: space, hyphen, space
  • capture: day number ($4)
  • capture: hyphen, month number, hyphen ($5)
  • capture: year number ($6)

Code: (Demo)

var_export(
    preg_replace(
        '~(\d{2})(-\d{2}-)(\d{4}) - (\d{2})(-\d{2}-)(\d{4})~',
        '$3$2$1 - $6$5$4',
        '25-05-2020 - 30-05-2020'
    )
);

Output:

'2020-05-25 - 2020-05-30'

Upvotes: 0

Urmat Zhenaliev
Urmat Zhenaliev

Reputation: 1547

Another solution:

<?php
$date = "25-05-2020 - 30-05-2020";

preg_match_all('/\d{1,2}-\d{1,2}-\d{4}/', $date, $matches);

list ($date1, $date2) = $matches[0];

echo $date1." ".$date2;

Demo

Upvotes: 1

nice_dev
nice_dev

Reputation: 17805

Just add a space before and after - like below:

<?php

$date = "25-05-2020 - 30-05-2020";
$splitted_dates = explode(" - ",$date);
$date1 = $splitted_dates[0];
$date2 = $splitted_dates[1];

echo $date1, " " , $date2;

Demo: https://3v4l.org/QTIHd

Upvotes: 1

Related Questions