简体   繁体   中英

Get only the filename from a path

I have this string

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

I want to change it to:

$string = 'file.ext';

Using PHP, I am trying to write a method that ignores everything left of the last \\ .

Use basename() with str_replace() as the \\ in the path is not recognized by basename()

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

Demo

Another solution is this:

Split the string by a delimiter( \\ ) to form an array: ['C:', 'Folder', 'Sub-Foler', 'file.ext'] using explode : explode("\\\\", $string);

Get the last element in the array using the end function, which you want as the result.

Put it all together:

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

Here's a demo: http://3v4l.org/i1du4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM