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
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.
Link to comment
Share on other sites

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!
Link to comment
Share on other sites

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.