从路径中提取文件名 [英] extract filename from path
问题描述
我需要从文件路径字符串获取文件名.例如,从该字符串\abc\def\filename.txt
我需要获取filename.txt
i need to get filename from file path string. For example, from this string \abc\def\filename.txt
i need to get filename.txt
尝试通过正则表达式执行此操作:
trying to do this with regexp:
$filepath="abc\filename.txt";
$filename = preg_replace("/.+\\/","",$filepath);
但是它给了我一个错误.我应该使用什么正则表达式来解决这个问题?
but it gives me an error. What regex i should use to solve this?
推荐答案
您应该改用函数基名:
$filepath = 'abc\filename.txt';
$filename = basename($filepath);
重要说明,当字符串中包含反斜杠时,您需要使用单引号,否则请正确地对它们进行转义.
edit: important note, you need to use single quotes when you have backslashes in your strings, else escape them properly.
注意:此将不起作用:
$filepath = "abc\filename.txt";
$filename = basename($filepath);
因为变量$ filepath实际上成立:
because you're variable $filepath infact holds:
abc[special char here equalling \f]ilename.txt
另一个 此正则表达式也适用..
another edit: this regex works too..
$filepath = '\def\abc\filename.txt';
$basename = preg_replace('/^.+\\\\/', '', $filepath);
原始文件的所有错误之处在于,您使用双引号而不是单引号,并且反斜杠需要转义两次(\\而不是\).
all that was wrong with your original was that you had double-quotes rather than single, and backslash needs double escaped (\\ rather than \).
这篇关于从路径中提取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!