tags:

views:

346

answers:

2

Hello there!

If I have a code like this:

$file = basename($filename);

How do i get the file extension of $file? The variabel file could contain any kind of file, like index.php or test.jpeg.

+7  A: 

Use the pathinfo() function:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";

or simply:

echo pathinfo($file, PATHINFO_EXTENSION);

You can of course look for the last "." in the filename and get everything after (relatively easy) but why reinvent the wheel?

cletus
+1  A: 
pathinfo($filename, PATHINFO_EXTENSION);
Ionuț G. Stan