Hi guys, i'm trying to work out the best way to remove a timestamp from a filename using php's string functions. The timestamp is split from the rest of the filename by an underscore on the left, and the dot to start the file extension on the right (e.g myfile_12343434.jpg) - I only ever want the text prior to the underscore although the length of this can vary. What's the best way to deal with this? Thanks!
+3
A:
edit to leave the extension intact (including e.g. .gd2 and .JPEG) do this:
$new = preg_replace("/_\\d+(\\.[a-z0-9]+)\$/i","\\1",$orig);
this effectively removes only the "_123" part, in a not-so-pretty way. For the purists among us, a version with a lookahead assertion, which only removes the timestamp:
$new = preg_replace("/_\\d+(?=\\.[0-9a-z]+\$)/i","",$orig);
mvds
2010-08-11 22:17:45
+1 for preg_replace, which will leave the rest of the filename intact (including the extension). However I'd use `preg_replace("/_\d+/","",$orig)` since we know the timestamp should be numeric.
JGB146
2010-08-11 22:20:02
@JGB: Uhm, this will also remove the extension which I thought was the question. I could be wrong though, in which case the `\d` is the perfect way to fix it.
mvds
2010-08-11 22:24:04
thanks for the suggestions guys - yeah i would like to preserve the extension too :) i'll play around with these suggestions to get a feel for how each one works
dan727
2010-08-11 22:28:29
@mvds: You're totally right. I completely misread the question and thought he also wanted the extension left intact.
JGB146
2010-08-11 22:30:01
@JGB: well, you're right after all, I'll update the answer.
mvds
2010-08-11 22:41:21
A:
The best way is to use preg_replace() to specify an exact match. A good start is something like the following (which will also preserve the extension):
$new = preg_replace("/_\d+/","",$orig);
But since this is a unix timestamp, we can do better by specifying the length of the numeric portion that it will match on:
$new = preg_replace("/_\d{1,11}/","",$orig);
JGB146
2010-08-11 22:26:30