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