views:

70

answers:

3

If I have filename.jpg, with PHP how would change it too filename123456789.jpg, where 123456789 is a timestamp, I currently do this,

$name = $filename;
$parts = explode(".", $name);
$filename = $parts[0].time().'.'.$parts[1];

however this just just leaves me with 123456789.

+7  A: 

Your approach works fine too, but breaks if the filename has multiple dots. I'd rather use the pathinfo() function to accomplish this:

$info = pathinfo($filename);
$filename = $info['filename'].time().'.'.$info['extension'];
Tatu Ulmanen
A: 

debug (output) your input and steps to find the error

function debug($var, $label = '') {
    echo $label
        . '<pre>'
        . print_r($var, true)
        . '</pre>';
}

$name = 'filename.bug.test.jpg';
debug($name, 'old filename');
$parts = explode('.', $name);
debug($parts, 'filenameparts');
$ext = array_pop($parts);
$prefix = implode('.', $parts);
$newName = $prefix . time() . '.' . $ext;
debug($newName, 'new filename');

as mention above use pathinfo instead of explode

i've used explode, couse i've used a dummy filename.

maggie
A: 

thats a no-brainer:

function getFileName($filename){
preg_match('#([^/]+)\.([\w]+)$#',$filename,$match);
return $match[1].time().'.'.$match[2];
}
Hannes
why involve preg_match() when pathinfo() exists?
Quamis
cause somebody else already did it, many roads lead to rome and all that
Hannes