PHP string manipulation help with timestamped files
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.开发者_Python百科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!
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);
You could use this:
$filename = explode("_", $orig_filename)[0];
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);
精彩评论