Extract Date from Filename PHP

Wednesday, November 4, 2015

I have a few hundred thousand files from a few different sources. Each one of the files has the date in the name, however, the filename structure differs for example:



2015-10-05-importsrc1.txt
20151004importsrc2.txt
importsrc3-154826-4521-2015-10-06.csv
importsrc4-154826-4521-20151006.txt


I need to deal with files that are of the current month and the next month ignoring any older files.



I have seen a few examples of how to check specific files using loops to check the date required however I am trying to avoid too many loops and potentially using regex to pattern match a date and then do a comparison.



Currently I use the following (where $f is the file name and extension):



//CHANGED THIS TO SKIP OLD ONES
if(strpos(str_replace("-", "", $f), "201510") == false)
{
continue;
}


But this only works for the previous month and is currently hard coded, ideally I need something like:



//CHANGED THIS TO SKIP OLD ONES
$extractedDate = preg_match('DATEPATTERN',(str_replace("-", "", $f), "201510"),$extractedDate );
if(strtotime($extractedDate[0]) < date('Y-m-d',(strtotime ('-1 Month', strtotime (date('Y-m-d)))))
{
continue;
}


I know I could simply alter my first attempt, add another condition and make it dynamic but if I were able to extract the date this would help in so many ways.

0 comments:

Post a Comment