从php中的几个字符串变量中提取多个日期格式

时间:2011-12-07 05:32:34

标签: php date

我需要从字符串变量中提取日期,并将日期格式化为各种格式,如下所示:

$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";

在提取正确的日期信息时,创建一个适用于上述所有输入变量的PHP函数的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

有关函数返回的DateTime对象的更多信息,请查看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";
}

答案 1 :(得分:0)

你可以使用下面的函数,它将匹配你所有的变量。

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);

输出将如您所愿:“03/12/2011”。

您还可以测试所有字符串:

$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";