Home > Backend Development > PHP Tutorial > How to Get the Current PHP Script File Name Without the Extension?

How to Get the Current PHP Script File Name Without the Extension?

Barbara Streisand
Release: 2024-11-14 21:41:02
Original
1004 people have browsed it

How to Get the Current PHP Script File Name Without the Extension?

Getting Current Script File Name Excluding Extension .php

When working with PHP scripts, it becomes necessary to retrieve the name of the currently executing file, often without its extension. This poses a challenge when the file's name follows a pattern like "jquery.js.php." Our goal is to extract only the "jquery.js" portion.

Solution:

PHP provides a magic constant called FILE that holds the current file's path. Combining this with the basename() function and specifying the ".php" extension for removal accomplishes our task:

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

Generic Extension Removal Function:

To remove extensions from arbitrary filenames, a more versatile function is preferred:

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

This approach utilizes PHP's pathinfo() function, which extracts the filename portion of a path or URL.

Alternative Approach Using Standard String Functions:

For enhanced efficiency, you can employ standard string functions:

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

This method leverages PHP's substr() and strrpos() functions to identify the position of the extension and create a truncated string. Both techniques provide reliable means of retrieving a file's name minus its extension, catering to different needs and optimization preferences.

The above is the detailed content of How to Get the Current PHP Script File Name Without the 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