Reputation: 42
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
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
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
Upvotes: 8