用于目录的PHP正则表达式

时间:2013-08-24 22:27:44

标签: php regex

我需要一个正则表达式,它将在最后一个正斜杠之后接受字符串。

例如,考虑到我有以下字符串:

C:/dir/file.txt

我只需要 file.txt 部分(字符串)。

谢谢:)

3 个答案:

答案 0 :(得分:5)

您不需要正则表达式。

$string = "C:/dir/file.txt";

$filetemp = explode("/",$string);

$file = end($filetemp);

编辑,因为我记得关于链接这些类型的函数的最新PHP吐出错误。

答案 1 :(得分:3)

如果您的字符串始终是路径,则应考虑basename()函数。

示例:

$string = 'C:/dir/file.txt';

$file = basename($string);

否则,其他答案都很棒!

答案 2 :(得分:1)

strrpos()函数查找字符串的最后一次出现。您可以使用它来确定文件名的起始位置。

$path = 'C:/dir/file.txt';
$pos  = strrpos($path, '/');
$file = substr($path, $pos + 1);
echo $file;