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');
Generic Extension Removal Function:
To remove extensions from arbitrary filenames, a more versatile function is preferred:
function chopExtension($filename) { return pathinfo($filename, PATHINFO_FILENAME); }
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, '.')); }
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!