Mostafa Elkady
Mostafa Elkady

Reputation: 5791

How to 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 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.

Upvotes: 265

Views: 391860

Answers (17)

anon
anon

Reputation:

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

Upvotes: 522

Dan Bray
Dan Bray

Reputation: 7822

Sometimes an extension contains more than one part. It may or may not be desirable to remove the entire extension. The function below removes the entire extension if you pass true as the second parameter:

function removeExt($path, $fullExt = false)
{
    if ($fullExt === false)
         return pathinfo($path, PATHINFO_FILENAME);
    $basename = basename($path);
    return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}

Eg:

echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file.tar
echo removeExt('https://example.com/file.tar.gz', true);
// https://example.com/file
echo removeExt('file.tar.gz');
// file.tar
echo removeExt('file.tar.gz', true);
// file
echo removeExt('file');
// file

Upvotes: 2

Subroto Biswas
Subroto Biswas

Reputation: 641

File extension extract from file:

File Name = subrotobiswas.jpg
$fileExtension = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION); //Output: jpg
$newNameOfFileWithoutExtension = basename( $_FILES["fileToUpload"]["name"], $fileExtension ); //Output: subrotobiswas
$fullFileName = $newNameOfFileWithoutExtension . "." .$fileExtension; // Output: subrotobiswas.jpg

Upvotes: -1

yckart
yckart

Reputation: 33398

https://php.net/manual/en/function.pathinfo.php

pathinfo($path, PATHINFO_FILENAME);

Simple functional test: https://ideone.com/POhIDC

Upvotes: 133

anydasa
anydasa

Reputation: 2623

If the extension is not known, use this solution

 pathinfo('D:/dir1/dir2/fname', PATHINFO_FILENAME); // return "fname"
 pathinfo('D:/dir1/dir2/fname.php', PATHINFO_FILENAME); // return "fname"
 pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "fname"

 pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_DIRNAME) . '/' . pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "D:/dir1/dir2/fname"

PHP MAN function pathinfo

Upvotes: 15

Rohan Khude
Rohan Khude

Reputation: 4883

Almost all the above solution have the shown getting filename from variable $path

Below snippet will get the current executed file name without extension

echo pathinfo(basename($_SERVER['SCRIPT_NAME']), PATHINFO_FILENAME);

Explanation

$_SERVER['SCRIPT_NAME'] contains the path of the current script.

Upvotes: 8

Hoàng Vũ Tgtt
Hoàng Vũ Tgtt

Reputation: 2032

in my case, i use below. I don't care what is its extention. :D i think it will help you

$exploded_filepath = explode(".", $filepath_or_URL);
$extension = end($exploded_filepath);
echo basename($filepath_or_URL, ".".$extension ); //will print out the the name without extension.

Upvotes: 3

shaz3e
shaz3e

Reputation: 334

Your answer is below the perfect solution to hide to file extension in php.

<?php
    $path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    echo basename($path, ".php");
?>

Upvotes: 0

mariovials
mariovials

Reputation: 786

Short

echo pathinfo(__FILE__)['filename']; // since php 5.2

Upvotes: 2

Jitendra Pawar
Jitendra Pawar

Reputation: 1321

You can write this

$filename = current(explode(".", $file));

These will return current element of array, if not used before.

Upvotes: 1

Ghanshyam Gohel
Ghanshyam Gohel

Reputation: 1274

If you don't know which extension you have, then you can try this:

$ext = strtolower(substr('yourFileName.ext', strrpos('yourFileName.ext', '.') + 1));
echo basename('yourFileName.ext','.'.$ext); // output: "youFileName" only

Working with all possibilities:

image.jpg // output: "image"
filename.image.png // output: "filename.image"
index.php // output: "index"

Upvotes: 1

Vincenzo Ruffa
Vincenzo Ruffa

Reputation: 17

This return only filename without any extension in 1 row:

$path = "/etc/sudoers.php";    
print array_shift(explode(".", basename($path)));
// will print "sudoers"

$file = "file_name.php";    
print array_shift(explode(".", basename($file)));
// will print "file_name"

Upvotes: 0

user2047861
user2047861

Reputation: 125

File name without file extension when you don't know that extension:

$basename = substr($filename, 0, strrpos($filename, "."));

Upvotes: 1

fire
fire

Reputation: 21531

@Gordon basename will work fine if you know the extension, if you dont you can use explode:

$filename = end(explode(".", $file));

Upvotes: 6

caiosm1005
caiosm1005

Reputation: 1725

Another approach is by using regular expressions.

$fileName = basename($filePath);
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

This removes from the last period . up until the end of the string.

Upvotes: 19

NSINE
NSINE

Reputation: 47

@fire incase the filename uses dots, you could get the wrong output. I would use @Gordon method but get the extension too, so the basename function works with all extensions, like this:

$path = "/home/httpd/html/index.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

$file = basename($path, ".".$ext); // $file is set to "index"

Upvotes: 3

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 224

Related Questions