[英]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']
使用explode
: explode("\\\\", $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.