graham23s Posted August 24, 2007 Share Posted August 24, 2007 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 More sharing options...
lemmin Posted August 24, 2007 Share Posted August 24, 2007 You can use basename() to strip the path and extension of a file. http://us2.php.net/manual/en/function.basename.php Link to comment https://forums.phpfreaks.com/topic/66566-replacing-an-extension/#findComment-333422 Share on other sites More sharing options...
Fadion Posted August 25, 2007 Share Posted August 25, 2007 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'. Link to comment https://forums.phpfreaks.com/topic/66566-replacing-an-extension/#findComment-333586 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.