user3807593
user3807593

Reputation: 42

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 \.

Upvotes: 1

Views: 54

Answers (2)

james
james

Reputation: 26271

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

Upvotes: 1

John Conde
John Conde

Reputation: 219794

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

Upvotes: 8

Related Questions