Home  >  Article  >  Backend Development  >  How to Extract a Script Filename Without its PHP Extension?

How to Extract a Script Filename Without its PHP Extension?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 12:35:02199browse

How to Extract a Script Filename Without its PHP Extension?

Extracting Script Filename Without PHP Extension

Getting the full script filename, including its extension, can be easily accomplished using PHP's magic constant __FILE__. However, if your goal is to obtain the filename without the ".php" extension, you need a slightly different approach.

Method 1: Using basename() with FILE

The basename() function can remove the extension from __FILE__. For example:

$filenameWithoutExtension = basename(__FILE__, '.php');

This will assign "jquery.js" to $filenameWithoutExtension for the given script name "jquery.js.php".

Method 2: Generic Extension Remover Function

You can also create a generic function that removes the extension from any filename:

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

Method 3: Substring and String Splitting

Another option is to use standard string library functions, like substr() and strrpos():

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

Performance Considerations

Benchmarking shows that using string functions is much faster than using pathinfo().

Example Usage

$filenameWithoutExtension = chopExtension('bob.php'); // "bob"
$filenameWithoutExtension2 = chopExtension('bob.i.have.dots.zip'); // "bob.i.have.dots"

The above is the detailed content of How to Extract a Script Filename Without its PHP Extension?. 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