PHP, get file name without file extension
Solution 1:
No need for all that. Check out pathinfo(), it gives you all the components of your path.
Example from the manual:
$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"; // filename is only since PHP 5.2.0
Output of the code:
/www/htdocs
index.html
html
index
And alternatively you can get only certain parts like:
echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
Solution 2:
As an alternative to pathinfo()
, you can use
-
basename()
— Returns filename component of path
Example from PHP manual
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
You have to know the extension to remove it in advance though.
However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.