簡體   English   中英

僅從路徑獲取文件名

[英]Get only the filename from a path

我有這串

$string = 'C:\Folder\Sub-Folder\file.ext';

我想將其更改為:

$string = 'file.ext';

使用PHP,我試圖編寫一種忽略最后\\剩下的所有內容的方法。

使用basename()str_replace()\\路徑不被認可的basename()

$filename = basename(str_replace('\\', '/', 'C:\Folder\Sub-Foler\file.ext'));
echo $filename; // file.ext

演示版

另一個解決方案是這樣的:

用分隔符( \\ )分割字符串以形成數組: ['C:', 'Folder', 'Sub-Foler', 'file.ext']使用explodeexplode("\\\\", $string);

使用end函數獲取數組中的最后一個元素,作為結果。

放在一起:

$string = 'C:\Folder\Sub-Foler\file.ext';
$stringPieces = explode("\\", $string);
$string = end($stringPieces);

這是一個演示:http: //3v4l.org/i1du4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM