tags:

views:

51

answers:

3

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
+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
@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
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
@mvds: You're totally right. I completely misread the question and thought he also wanted the extension left intact.
JGB146
@JGB: well, you're right after all, I'll update the answer.
mvds
A: 

You could use this:

$filename = explode("_", $orig_filename)[0];
AHM
you can't extract the first element of the array this way, you have to use an intermediate variable :$a = explode("_", $orig_filename);$filename = $a[0];
darma
@darma - You don't "have to". For example: list($filename) = explode('_', $orig_filename);
GZipp
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