两种解决方案:
- preg_match()
-
str_replace() 与 pathinfo()
1:preg_match()
好的,问题是您使用了反斜杠。您必须确保不要使用双引号来定义您的文件路径,因为反斜杠被解释为转义序列。使用单引号。
此外,使用正则表达式,通过从路径后面移动直到遇到反斜杠来获取文件名非常简单......诀窍是反斜杠是 \\\\.. here's why
最后,您不想使用 preg_replace。只需使用 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() 和 pathinfo()
正如其他人所说,basename() 是一个不错的选择。另一种选择,如果您以后可能还需要目录或其他路径信息,请使用pathinfo()
问题是 basename 和 pathinfo 都假定为正斜杠,因此您必须将反斜杠转换为正斜杠:
例子:
<?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
?>