如何取得目前PHP腳本檔名(不含副檔名)?

Barbara Streisand
發布: 2024-11-14 21:41:02
原創
917 人瀏覽過

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');
登入後複製

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板