Unix Man Unix Man - 1 year ago 208
PHP Question

PHP, get file name without file extension

I have this PHP code:

function ShowFileExtension($filepath)
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];

$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

if(count($pattern) > 1)
$filenamepart = $pattern[count($pattern)-1][0];
preg_match('/[^?]*/', $filenamepart, $matches);
return strtolower($matches[0]);

If I have a file named
, this function returns

I want to do the reverse, I want the function to return
without the extension.

The file is just a string in a variable.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download