简体   繁体   中英

Extract Date from Filename PHP

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.

I have been unsuccessful finding anything on the web on how to do this. It seems there is no exact science. Using the comments above I have the following regex which works to match the files specified:

$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]);
print_r($date);

There are three patterns to match 20151001 , 01102015 , 2015-10-01 , 01-10-2015 . From here I will be able to do a comparison of the date.

This is certainly not a definitive answer, but may help someone in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM