PHP 檔案系統 basename() 函式



PHP 檔案系統basename()函式允許您從完整路徑中僅提取檔名稱。它通常用於從完整路徑字串中提取檔名。

basename()的主要目標是在忽略先前目錄名稱的同時提取路徑的尾隨名稱元件。

假設您知道檔案的完整地址,例如“C:/documents/picture.jpg”。如果您只需要“picture.jpg”檔名,則可以使用basename()來實現此目的。

語法

以下是 PHP 檔案系統basename()函式的語法 -

string basename ( string $path [, string $suffix ] )

引數

下面提到了使用basename()函式所需的的引數 -

序號 引數及說明
1

path(必需)

需要從中提取檔名的路徑字串。

2

suffix(可選)

此後綴將從提取的檔名中刪除。

返回值

它返回提取的檔名作為字串。

PHP 版本

basename()函式是 PHP 核心的一部分,在 PHP 4、PHP 5、PHP 7 和 PHP 8 中可用。

示例

在此示例中,我們將使用 PHP 檔案系統basename()函式來簡單地提取路徑中提供的檔名,並列印帶副檔名和不帶副檔名的檔名。因此,我們將使用basename()從路徑中刪除檔名元件,然後再將其提供給 $file 變數。

<?php

   // specify the directory path here
   $path = "/Applications/XAMPP/xamppfiles/htdocs/mac/index.php";

   //  $file is set to "index.php"
   $file = basename($path);  

   // This will print "Full file name: index.php"
   echo "Full file name: " . $file . "<br>"; 

   // $file is set to "index"
   $file = basename($path, ".php");  

   // This will print "File name without extension: index"
   echo "File name without extension: " . $file; 

?>

輸出

這將產生以下結果 -

Full file name: index.php
File name without extension: index

示例

現在,我們將使用basename()函式處理不同的副檔名。因此,在這裡我們可以使用此函式處理不同的副檔名。basename()函式將獲取每個程式碼中提到的路徑的檔名,但不包括其副檔名。

<?php
   // specify the directory path here
   $path1 = "/Applications/XAMPP/xamppfiles/htdocs/mac/index.php";
   $path2 = "/Applications/XAMPP/xamppfiles/htdocs/mac/myfile.txt";
   $path3 = "/Applications/XAMPP/xamppfiles/htdocs/mac/logo.gif";

   // Filename without extension: php
   echo "Filename without extension: " . basename($path1, ".php") . "<br>"; 

   // Filename without extension: text
   echo "Filename without extension: " . basename($path2, ".txt") . "<br>"; 

   // Filename without extension: gif
   echo "Filename without extension: " . basename($path3, ".gif") . "<br>"; 

?> 

輸出

這將產生以下結果 -

Filename without extension: index
Filename without extension: myfile
Filename without extension: logo

示例

處理 URL 最有可能指的是如何處理包含查詢引數的 URL 的特定示例。因此,解析 URL 以使用 parse_url() 函式獲取路徑,然後使用basename()提取並列印檔名。

<?php
   // specify the directory path here
   $url = "/Applications/XAMPP/xamppfiles/htdocs/mac/index.php?version=1";

   // Parse the URL to get the path
   $parsed_url = parse_url($url, PHP_URL_PATH);

   // Use basename() on the path to get the file name
   $filename = basename($parsed_url);

   echo "Filename: " . $filename;
?> 

輸出

這將導致以下結果 -

Filename: index.php

示例

因此,basename()函式也可以處理其中包含多個點的檔名。因此,我們只需將目錄路徑傳遞給basename()即可獲得此功能。

以下是此示例的簡單演示 -

<?php
   // specify the directory path here
   $path = "/Applications/XAMPP/xamppfiles/htdocs/mac/file.with.dots.txt";

   // use basename() function to extract the filename
   $filename = basename($path);

   // Output: Filename: file.with.dots.txt
   echo "Filename: " . $filename; 
?> 

輸出

這將產生以下結果 -

Filename: file.with.dots.txt

總結

PHP basename()函式是一個非常有用的功能,用於提取給定路徑字串的檔名部分。實際上,它為使用者提供了一個選項,可以選擇在最後刪除任何指定的要提取的字尾。

php_function_reference.htm
廣告