Jump to content

replacing an extension


graham23s

Recommended Posts

Hey Guys,

 

what im trying to do here is when a user uploads a file, if they don't manually type a file name, the scripts takes the name of the uploaded file as the file name but it adds the extension on, is there a way i can take the .extension away from the file

 

i have:

 

     if(empty($file_name)) {
     
     $file_name = $txtfilename;
     
     } else {
     
     $file_name = $_POST['file_name'];
     
     }

 

any help would be appreciated

 

thanks guys

 

Graham

Link to comment
https://forums.phpfreaks.com/topic/66566-replacing-an-extension/
Share on other sites

Dont think basename() will do it, or at least i dont know how to use it:

 

$file = 'myfile.jpg';
echo basename($file, '.jpg'); //it will echo 'myfile'

 

U have to know the extension and even though u will get the filename, and u need the extension. I personally use:

$file = 'myfile.jpg';
$ext = strtolower(substr(strrchr($file, '.'), 1)); //it will echo jpg
$filename = substr($file, 0, strlen($file) - 4); //it will echo myfile
//or
$filename = basename($file, ".$ext"); //it will echo myfile

 

For the extension, it takes the last occurence of '.', shifts one character to the right and converts it all to lower case. For the filename it takes the string from the first character to the length of the string - 4 chars (removing the three chars extension and dot). The other thing is using basename.

 

Another simpler but not as reliable is explode():

$file = 'myfile.jpg';
$arr = explode('.', $file);
$filename = $arr[0];
$ext = $arr[1];

 

With this u cant have 'myfile.isthis.jpg'.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.