Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strip unknown file extension

I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

like image 360
Web_Designer Avatar asked Jun 02 '11 14:06

Web_Designer


2 Answers

You can extract the extension using pathinfo and cut it off.

// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");

Note the . before $ext

like image 26
galymzhan Avatar answered Nov 16 '22 08:11

galymzhan


pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.

$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);

The value of $filename will be file.

like image 128
kapa Avatar answered Nov 16 '22 08:11

kapa