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
Mary-Kate OlsenOriginal
2024-11-09 06:30:02752browse

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');

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);
}

Using this function:

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

Standard String Functions:

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

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

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!

Statement:
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