Jump to content

[SOLVED] grab name of file with most recent date in it


Recommended Posts

I wish to get the file name which has the most recent date in it.

 

all files are in the following format... (dd/mm/yyy)

 

abc - 21-09-2009 - Agenda.pdf

 

but it is not getting the correct file for some reason, this is what code i am using to get the filename.

 

	$files = glob('agendas/*.pdf');
	$datestring = strtotime(basename(substr($files[0], 14, 10),".pdf"));
	$anchortext = date('j M Y',$datestring);
	// echo(".".basename(substr($files[0], 14, 10),".pdf").".");
	$url = date('dmY',$datestring);
		if (strlen(date('j',$datestring)) == 1) { ?>  <?
		} ?><strong><?=$anchortext;?></strong>

I would probably take this approach

$sortfile = array();
foreach($files as $file){
    //Extract date
    if (preg_match('/(\d+)-(\d+)-(\d+)[^.]*?\.pdf/', $file, $reg)) {
        //add date to array (file as key)
        $sortfile[$file] = mktime(0,0,0,$reg[2],$reg[1],$reg[3]);
    }
}
asort($sortfile); //Sort an array (the dates) and maintain index association (file names)

//echo files
foreach($sortfile as $file => $fdate){
   echo "$file<br>";
}

 

EDIT: updated regex and changed strtotime to mkdate

 

please note this is untested, but the last file should be the one you want, or use arsort and it will be the first one :P

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.