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.
以上是如何取得目前PHP腳本檔名(不含副檔名)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!