Two solutions:
- preg_match()
- str_replace() with pathinfo()
1: preg_match()
Ok, so the problem is that you are using backslashes. You have to make sure that you do not use double quotes for defining your filepath, since the backslash is interpreted as an escape sequence. Use single quotes.
Additionally, with a regex, it's much simple to get a filename by moving from the back of the path until you hit a backslash.... the trick is that a backslash is \\\\
.. here's why
Finally, you don't want to use preg_replace. Just find the filename with preg_match:
<?php
// Use single quotes or the backslash will be interpreted as an esacpe sequence
$filepath = '\abc\def\filename.txt';
// You have to use 4 backslashes to represent your single backslash
// The regex picks the characters that are NOT \ from the end of the path
$pattern = '/[^\\\\]+$/';
// Use $matches to store the match
preg_match($pattern, $filepath, $matches);
// Display answer now, or use later
echo $matches[0];
?>
2: str_replace() with pathinfo()
As others said, basename()
is a good option. Another option, if there's any chance that you may also need the directory or other path information later down the line is to use pathinfo()
The problem is that both basename and pathinfo assume forward slashes, so you must convert your backslashes to forward slashes:
Example:
<?php
// Make sure to use single quotes
$filepath='abc\filename.txt';
// Replace backslash with forward slash
$filepath = str_replace('\\', '/', $filepath);
$path_parts = pathinfo($filepath);
// This is the answer you want
echo $path_parts['basename'], "\n";
// But you also have access to these
echo $path_parts['dirname'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>