How to get file name without file extension?

file, php, string

Solution

No need for all that. Check out pathinfo(), it gives you all the components of your path.

$filename = pathinfo($filepath, PATHINFO_FILENAME);

will give you the filename without extension.

Some other examples 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

Problem

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 `my.zip`, this function returns `.zip`. I want to do the reverse, I want the function to return `my` without the extension. The file is just a string in a variable.

Original source

Related problems