Home > Backend Development > PHP Tutorial > How to Extract the Filename Without Extension in PHP?

How to Extract the Filename Without Extension in PHP?

Mary-Kate Olsen
Release: 2024-11-09 06:30:02
Original
688 people have browsed it

How to Extract the Filename Without Extension in PHP?

Extracting the Filename Without Extension in PHP

Getting the filename of the currently executed script in PHP is easy with the magic constant __FILE__. However, if you need to extract the filename without its extension, such as the ".php" suffix, the process is slightly different.

The basename() Solution:

To remove the extension using the basename() function, you can:

basename(__FILE__, '.php');
Copy after login

This will return the filename without the .php extension, such as "jquery.js" for the string "jquery.js.php".

A Generic Extension Remover:

For a more versatile solution that can handle any file extension, you can define a custom function:

function chopExtension($filename) {
    return pathinfo($filename, PATHINFO_FILENAME);
}
Copy after login

Using this function:

var_dump(chopExtension('bob.php')); // "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // "bob.i.have.dots"
Copy after login

Standard String Functions:

Finally, you can use standard string functions for a quicker approach:

function chopExtension($filename) {
    return substr($filename, 0, strrpos($filename, '.'));
}
Copy after login

The above is the detailed content of How to Extract the Filename Without Extension in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template