Rename a file and keep file extension

Hi,

As in title, I need to rename a file with php, so here's the code
$file = "filenamehere.pdf"'
$file_extension = /* I need a help here */
rename("$file", "renamedfile".$file_extension);
All I need is a code which will recognize file extension of $file;
Or maybe there's some easier way to do this?

Thanks for any help.
LVL 8
ZadoAsked:
Who is Participating?
 
Marco GasiConnect With a Mentor FreelancerCommented:
Simply do

$file_extension = $array[count($array)-1];

This will return the last element of the array, the extension ;-)
0
 
Marco GasiConnect With a Mentor FreelancerCommented:
Use this

$array = explode($file, '.');
$file_extension = $array[1];

Cheers
0
 
ZadoAuthor Commented:
Can I reverse the results somehow? I mean if you have a file like 'some.file.jpg', then your script wouldn't work, but if we can reverse the results, I mean the array would be then

jpg
file
some

instead

some
file
jpg

then $array[0] would always mean file extension, but I'm not sure how to do this.
Thanks.
0
 
ZadoAuthor Commented:
Excellent, thanks a lot.
Btw, there's a small misspell in your code:
instead
$array = explode($file, '.');

Open in new window

there should be
$array = explode('.', $file);

Open in new window

0
 
Marco GasiFreelancerCommented:
oooops, you're right! anyway, I'm glad to help you. On to the next.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.