1

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

jcuenod
  • 55,835
  • 14
  • 65
  • 102
user3807593
  • 42
  • 1
  • 7
  • duplicate: http://stackoverflow.com/questions/1418193/how-to-get-file-name-from-full-path-with-php – Sky Jun 04 '15 at 20:54

2 Answers2

8

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

John Conde
  • 217,595
  • 99
  • 455
  • 496
1

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

james
  • 26,141
  • 19
  • 95
  • 113