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

How to Extract a Script Filename Without its PHP Extension?

Patricia Arquette
Release: 2024-11-09 12:35:02
Original
244 people have browsed it

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');
Copy after login

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);
}
Copy after login

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, '.'));
}
Copy after login

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"
Copy after login

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!

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