Home >Backend Development >PHP Tutorial >How to Remove the Extension from a Filename in PHP?

How to Remove the Extension from a Filename in PHP?

DDD
DDDOriginal
2024-11-10 02:11:02300browse

How to Remove the Extension from a Filename in PHP?

Extracting Filename without Extension in PHP

To obtain the filename of the currently executed PHP script without its ".php" extension, you can utilize the PHP magic constant __FILE__. However, it appears that you require the filename without the extension.

Solution 1: Using basename()

To accomplish this, you can employ the basename() function:

basename(__FILE__, '.php');

For instance, provided the script filename "jquery.js.php," this code would output "jquery.js."

Solution 2: Generic Extension Remover Function

A more versatile solution would be to create a function that strips the extension from any filename irrespective of its type:

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

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

Solution 3: Using String Library Functions

For enhanced speed, you can opt for standard string library functions:

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

The above is the detailed content of How to Remove the Extension from a Filename 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