从php中的几个字符串变量中提取多个日期格式 [英] Extract multiple date format from few string variables in php

查看:191
本文介绍了从php中的几个字符串变量中提取多个日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串变量中提取日期,日期格式如下:

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

创建PHP函数的最佳方式是什么,该函数将适用于上述所有输入变量,正确的日期信息?

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?

推荐答案

有关函数返回的DateTime对象的更多信息,请检查 DateTime class 的PHP文档

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

这篇关于从php中的几个字符串变量中提取多个日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆