Jump to content

i want to append a date to a filename


emehrkay

Recommended Posts

i have never written any expressions (its on the top, maybe third (its definitley behind mastering oo javascript), of my list of things to learn), but i just want to write a method in my upload class that would add _mmddyyyy to my file name. filename_xxx.ext where _xxx is what im adding

i could explode by period, loop through ad it before the extension and all that jazz or use substring, strchr etc, but im sure there is a simple regex way.

any help?

thank you
Link to comment
https://forums.phpfreaks.com/topic/30271-i-want-to-append-a-date-to-a-filename/
Share on other sites

[code]$file = "filename.ext";
$date = date('mdY');
$newfile = preg_replace('/(\.ext)$/', "_$date$1", $file);
print_r($newfile);
[/code]
Or you can hard-code the date into the $date variable. Depending on your extension structure, you could add some alternation:
[code]preg_replace('/(\.(?:ext|jpg|exe|dll|dat|doc|xls))$/', "_$date$1", $file)[/code]
or if you have files like "filename.dat1, filename.dat2, filename.dat3..."
[code]preg_replace('/(\.dat[0-9])$/', "_$date$1", $file)[/code]
Regex will let you be pretty specific.
In that case, you have a couple of options. Since I really have no idea what you're dealing with, this is the most general solution I can come up with at the moment.
[code]$newfile = preg_replace('/(\.[^.]+)$/', "_$date$1", $file);[/code]
You might be able to get away with this, but its a risky venture. It will match things like:
[code]filename.ext
file.html
new.season.0301.avi
file.dat
blah.c[/code]Which is what you want. But it'll also match things like:
[code].bashrc
.bash_profile[/code]
So as long as your file list is good, you shouldn't have any problems.

Glad to help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.