• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 304
  • Last Modified:

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.
0
Zado
Asked:
Zado
  • 3
  • 2
2 Solutions
 
Marco GasiFreelancerCommented:
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
 
Marco GasiFreelancerCommented:
Simply do

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

This will return the last element of the array, the extension ;-)
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now