I am working on extracting the date from filenames
. For this I have used regex.
The dates can appear like 2015-10-31
,20151031
, 31-10-2015
,31102015
.
Here is the code I am using to extract the date:
$re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';
$str = "20151001-importsrc1.txt";
$str = "2015-10-01-importsrc1.txt";
$str = "01-10-2015-importsrc1.txt";
$str = "importsrc1-2015-10-01.txt";
$str = "importsrc1-01102015.txt";
$str = "importsrc1-01-10-2015.txt";
preg_match($re, $str, $matches);
$date = str_replace("-", "", $matches[0]);
Using the str_replace
I am stripping the hyphens, therefore I end up with one of two formats, 20151031
, 31102015
.
Using strtotime()
it is converting to 1970
. Using PHP's DateTime
I received the following error:
Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (01102015) at position 7 (5): Unexpected character'
I need to avoid createfromformat
from what I understand, but as I only have a date and not datetime this is erroring.
Can anyone point me in the right direction as to how I could format these dates for use later in the code.
If you only have those four formats only then you can create a custom function like as
function check_format($string) {
$string = preg_replace('/(-?importsrc1-?)|(.txt)/','',$string);
if (preg_match('/(\d){4}-(\d){2}-(\d){2}/', $string)) {
$date = DateTime::createFromFormat('Y-m-d', $string);
} elseif (preg_match('/(\d){2}-(\d){2}-(\d){4}/', $string)) {
$date = DateTime::createFromFormat('d-m-Y', $string);
} elseif (preg_match('/..\K(\d{2})/', $string, $m)) {
if ($m[0] > 12) {
$date = DateTime::createFromFormat('Ymd', $string);
} else {
$date = DateTime::createFromFormat('dmY', $string);
}
}
return $date->format('Y-m-d');
}
Do not strip hyphens. So, the next code will work fine.
$date1 = new \DateTime('31-10-2015');
$date2 = new \DateTime('2015-10-31');