[php] 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 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.

This question is related to php file string

The answer is


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

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

The existing solutions fail when there are multiple parts to an extension. The function below works for multiple parts, a full path or just a a filename:

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

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

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.


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

pathinfo($path, PATHINFO_FILENAME);

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


There is no need to write lots of code. Even it can be done just by one line of code. See here

Below is the one line code that returns the filename only and removes extension name:

<?php
 echo pathinfo('logo.png')['filename'];
?>

It will print

logo

Source: Remove extension and return only file name in PHP


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.


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


@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"

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"

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");
?>

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.

You can write this

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

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


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"

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.


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

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


Short

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript