php filename without extension
basename
(PHP 4, PHP 5, PHP 7, PHP 8)
basename — Возвращает последний компонент имени из указанного пути
Описание
При передаче строки с путём к файлу или каталогу, данная функция вернёт последний компонент имени из данного пути.
Список параметров
На платформах Windows в качестве разделителей имён директорий используются оба слеша (прямой / и обратный \ ). В других операционных системах разделителем служит прямой слеш ( / ).
Возвращаемые значения
Примеры
Пример #1 Пример использования функции basename()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 30 notes
It’s a shame, that for a 20 years of development we don’t have mb_basename() yet!
There is only one variant that works in my case for my Russian UTF-8 letters:
If your path has a query string appended, and if the query string contains a «/» character, then the suggestions for extracting the filename offered below don’t work.
In such a case, use:
It might be useful to have a version of the function basename working with arrays too.
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.
// your file
$file = ‘image.jpg’ ;
There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section «Handling file uploads» uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):
If you want the current path where youre file is and not the full path then use this 🙂
www dir: domain.com/temp/2005/january/t1.php
Exmaple for exploding 😉 the filename to an array
A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))
since basename always treats a path as a path to a file, e.g.
/var/www/site/foo/ indicates /var/www/site as the path to file
foo
Even though yours is shorter, you can also do:
$ext = end(explode(«.», basename($file
Additional note to Anonymous’s mb_basename() solution: get rid of trailing slashes/backslashes!
echo mb_basename ( «/etc//» ); # «etc»
?>
I got a blank output from this code
suggested earlier by a friend here.
So anybody who wants to get the current directory path can use another technique that I use as
//suppose you’re using this in pageitself.php page
once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:
On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:
//assume the real filename is mytest.JPG:
Because of filename() gets «file.php?var=foo», i use explode in addition to basename like here:
to get the base url of my website
Basename without query string:
Getting file names without extensions
When getting file names in a certain folder:
14 Answers 14
Although I am surprised there isn’t a way to get this directly from the FileInfo (or at least I can’t see it).
This solution also prevents the addition of a trailing comma.
I dislike the DirectoryInfo, FileInfo for this scenario.
DirectoryInfo and FileInfo collect more data about the folder and the files than is needed so they take more time and memory than necessary.
This returns the file name only without the extension type. You can also change it so you get both name and the type of file
As an additional answer (or to compound on the existing answers) you could write an extension method to accomplish this for you within the DirectoryInfo class. Here is a sample that I wrote fairly quickly that could be embellished to provide directory names or other criteria for modification, etc:
Edit: I also think this method could probably be simplified or awesome-ified if it used LINQ to achieve the construction of the array, but I don’t have the experience in LINQ to do it quickly enough for a sample of this kind.
Edit 2 (almost 4 years later): Here is the LINQ-ified method I would use:
FileInfo knows its own extension, so you could just remove it
or if you’re paranoid that it might appear in the middle, or want to microoptimize:
if file name contains directory and you need to not lose directory:
Just for the record:
Below is my code to get a picture to load into a PictureBox and Display a Picture name in to a TextBox without Extension.
You can make an extension method on FileInfo:
Answering the original question:
Say you want to get all files with a certain name:
How can I change a file’s extension using PHP?
How can I change a file’s extension using PHP?
Ex: photo.jpg to photo.exe
11 Answers 11
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
Will change any extension to what you want. Replace png with what ever your desired extension would be.
Replace extension, keep path information
Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here’s a small function that’ll do that:
Then use the rename() function to rename the file with the new filename.
Just replace it with regexp:
You can also extend this code to remove other image extensions, not just bmp:
For regex fans, modified version of Thanh Trung’s ‘preg_replace’ solution that will always contain the new extension (so that if you write a file conversion program, you won’t accidentally overwrite the source file with the result) would be:
Changes made only on extension part. Leaves other info unchanged.
Or for all extensions:
Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:
Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn’t beat substr_replace :
Using ‘find’ to return filenames without extension
I have a directory (with subdirectories), of which I want to find all files that have a «.ipynb» extension. But I want the ‘find’ command to just return me these filenames without the extension.
I know the first part:
But how do I then get the names without the «ipynb» extension? Any replies greatly appreciated.
9 Answers 9
To return only filenames without the extension, try:
however invoking basename on each file can be inefficient, so @CharlesDuffy suggestion is:
Using + means that we’re passing multiple files to each bash instance, so if the whole list fits into a single command line, we call bash only once.
To print full path and filename (without extension) in the same line, try:
To print full path and filename on separate lines:
Here’s a simple solution:
I found this in a bash oneliner that simplifies the process without using find
If you need to have the name with directory but without the extension :
If there’s no occurrence of this «.ipynb» string on any file name other than a suffix, then you can try this simpler way using tr :
If you don’t know that the extension is or there are multiple you could use this:
and for a list of files with no duplicates (originally differing in path or extension)
Another easy way which uses basename is:
Using + will reduce the number of invocations of the command (manpage):
support multiple arguments and treat each as a NAME
How to remove extension from string (only real extension!)
I’m looking for a small function that allows me to remove the extension from a filename.
Look at these scripts,
When we add the string like this:
It will return only «This».
The extension can have 3 or 4 characters, so we have to check if dot is on 4 or 5 position, and then remove it.
How can it be done?
18 Answers 18
So, this matches a dot followed by three or four characters which are not a dot or a space. The «3 or 4» rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.
Outputs: string(4) «test»
This is a rather easy solution and will work no matter how long the extension or how many dots or other characters are in the string.
It’s similar to one of your googled examples but simpler, faster and easier than regular expressions and the other examples. Well imo anyway. Hope it helps someone.
Recommend use: pathinfo with PATHINFO_FILENAME
You could use what PHP has built in to assist.
If you don’t have a path, but just a filename, this will work and be much terser.
The following code works well for me, and it’s pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.
I found many examples on the Google but there are bad because just remove part of string with «.»
Actually that is absolutely the correct thing to do. Go ahead and use that.
There are a few ways to do it, but i think one of the quicker ways is the following
Another solution is this. I havent tested it, but it looks like it should work for multiple periods in a filename
As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me.
This works when there is multiple parts to an extension and is both short and efficient:
You can set the length of the regular expression pattern by using the
But I don’t think you really need it. What will you do with a file named «This.is»?
Try to use this one. it will surely remove the file extension.
EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
Landed on this page for looking for the fastest way to remove the extension from a number file names from a glob() result.
So I did some very rudimentary benchmark tests and found this was the quickest method. It was less than half the time of preg_replace() :
The basic benchmark test code and the results: