0

I need to extract the date out of a string variable, and the date are formatted in various kind of formats as below:

$date1 = "03/12/2011 (Sat)";
$date2 = "3.12.2011 SAT";
$date3 = "Date: 03/12/2011 "; /* <-- the extra trailing space is intentional */
$date4 = "date:03/12/2011";
$date5 = "date: 03/12/2011";
$date6 = "03/12/2011";
$date7 = "13.12.2011 TUE";

What is the best way to create a PHP function which will work for all the input variables above in extracting the correct date info?

Dennis
  • 3,528
  • 4
  • 28
  • 40

2 Answers2

2

For more info on the DateTime object returned by the function, check the PHP documentation for the DateTime class.

/**
 * Parses date from string
 * @param string $str Uncorrected date string
 * @return DateTime PHP datetime object
 */
function date_grab($str)
{
  // regex pattern will match any date formatted dd-mm-yyy or d-mm-yyyy with
  // separators: periods, slahes, dashes
  $p = '{.*?(\d\d?)[\\/\.\-]([\d]{2})[\\/\.\-]([\d]{4}).*}';
  $date = preg_replace($p, '$3-$2-$1', $str);
  return new \DateTime($date);
}

// verify that it works correctly for your values:
$arr = array(
  "03/12/2011 (Sat)",
  "3.12.2011 SAT",
  "Date: 03/12/2011 ", /* <-- the extra trailing space is intentional */
  "date:03/12/2011",
  "date: 03/12/2011",
  "03/12/2011"
);

foreach ($arr as $str) {
  $date = date_grab($str);
  echo $date->format('Y-m-d') . "\n";
}
  • thanks @rdlowrey, but it seems there is some bug in the code, it will only work for 'day' which is less than 10, e.g: "13/12/2011" become "2011-12-03" and "3.5.2011 THU"-->"2011-05-07" – Dennis Dec 07 '11 at 06:04
  • i changed the pattern to $date = preg_replace('/.*([\d]{2}).([\d]{2}).([\d]{4}).*/', '$3-$2-$1', $str); and is working fine now :) – Dennis Dec 07 '11 at 06:14
  • @Dennis I just updated the regex pattern sorry about that. I forgot to make the first * quantifier ungreedy. I just tested the *corrected* code in the answer and it works as expected now. The regex you just commented above actually will not work in the event there is only a single number for the day portion of the month. –  Dec 07 '11 at 06:17
0

you can use the below function, it will match all the variables you spcecified.

function extractDates($mydate)
{
    $date = explode(" ", $mydate);
    $output = $date[0];
    if ($date[0] == "Date:" || $date[0] == "date:")
    {
        $output = $date[1];
    }

    return $output;
}

$date1 = "Date: 03/12/2011";
echo extractDates($date1);

The output will be as you expected: "03/12/2011".

You can also test all your strings:

$date1 = "03/12/2011 (Sat)";
$date2 = "3.12.2011 SAT";
$date3 = "Date: 03/12/2011 "; /* <-- the extra trailing space is intentional */
$date4 = "date:03/12/2011";
$date5 = "date: 03/12/2011";
$date6 = "03/12/2011";
$date7 = "13.12.2011 TUE";
William-H-M
  • 1,050
  • 1
  • 13
  • 19
Manigandan Arjunan
  • 2,260
  • 1
  • 25
  • 42