Extract file name without file extension in PHP
This article demonstrates how to extract file names without file extensions in PHP.
1. Using pathinfo() function
The pathinfo() function returns all the components of your path. It returns an associative array containing dirname, basename, extension, and filename information.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $path = '/home/cache/index.html'; $filename = pathinfo($path); print_r($filename); /* Output: Array ( [dirname] => /home/cache [basename] => index.html [extension] => html [filename] => index ) */ ?> |
You may also specify a flag to the pathinfo() function to retrieve path information for a single component. This flag can be one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME. To extract the filename component of the path, you can use pathinfo() with the PATHINFO_FILENAME flag.
|
1 2 3 4 5 6 |
<?php $path = '/home/cache/index.html'; $filename = pathinfo($path, PATHINFO_FILENAME); echo $filename; ?> |
2. Using basename() function
You may also use the basename() function, which returns the base name of the given path. It optionally takes a suffix, which will be removed from the result if the name component ends with it. For example,
|
1 2 3 4 5 6 |
<?php $path = '/home/cache/index.html'; $filename = basename($path, ".html"); echo $filename; ?> |
3. Using preg_replace() function
Another alternative is to use regular expressions for this task. In PHP, you can use the preg_replace() function, as demonstrated below:
|
1 2 3 4 5 6 |
<?php $path = '/home/cache/index.html'; $fileName = preg_replace("/.[^.]+$/", "", basename($path)); echo $fileName; ?> |
That’s all there is to extracting file names without file extensions in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)