php 从路径中提取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3278120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:12:36  来源:igfitidea点击:

extract filename from path

phpregex

提问by nukl

i need to get filename from file path string. For example, from this string \abc\def\filename.txti need to get filename.txt

我需要从文件路径字符串中获取文件名。例如,从这个字符串\abc\def\filename.txt我需要得到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?

但它给了我一个错误。我应该使用什么正则表达式来解决这个问题?

回答by nathan

you should use the function basename instead:

您应该使用函数 basename 代替:

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

编辑:重要说明,当字符串中有反斜杠时需要使用单引号,否则正确转义它们。

note: this will notwork:

注意:这不起作用:

$filepath = "abc\filename.txt";
$filename = basename($filepath);

because you're variable $filepath infact holds:

因为你是变量 $filepath 事实上持有:

abc[special char here equalling \f]ilename.txt

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

你原来的所有错误是你有双引号而不是单引号,并且反斜杠需要双转义(\\而不是\)。

回答by Peter Ajtai

Two solutions:

两种解决方案:

  1. preg_match()
  2. str_replace()with pathinfo()
  1. preg_match()
  2. str_replace()pathinfo()


1: preg_match()

1:preg_match()

Ok, so the problem is that you are using backslashes. You have to make sure that you do not use double quotesfor 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:

最后,您不想使用 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()with pathinfo()

2: str_replace()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()

正如其他人所说,basename()是一个不错的选择。另一种选择,如果您以后可能还需要目录或其他路径信息,则使用pathinfo()

The problem is that both basename and pathinfo assume forward slashes, so you must convert your backslashes to forward slashes:

问题是 basename 和 pathinfo 都假定为正斜杠,因此您必须将反斜杠转换为正斜杠:

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
?>

回答by Sarfraz

This should do it:

这应该这样做:

$filepath='abc\filename.txt';
$basename = preg_replace('/^.+[\\\/]/', '', $filepath);
echo $basename;

Result:

结果:

filename.txt

回答by Jet

preg_replace("/[^\/]+.([^\.]+\.[a-z]{3,5})/i","","abc/filename.txt"); //return filename.txt

回答by Billy ONeal

Why throw regex at such a simple problem?

为什么在这么简单的问题上抛出正则表达式?

$source = "/i/am/a/path.txt";
$pos = strrpos($source, '/');
$result = substr($source, $pos === FALSE ? 0 : $pos);

EDIT: I have not tried this -- I don't have a working PHP server handy. There mightbe an off-by-one error with substr and strrpos, but if that's the case you just add or subtract one from $pos.

编辑:我没有试过这个——我手边没有一个可用的 PHP 服务器。有可能是差一错误与SUBSTR和strrpos,但如果是这样的话,你只需加一或减一$pos

EDIT2: Here's a backslash version:

EDIT2:这是一个反斜杠版本:

$source = "\i\am\a\path.txt";
$pos = strrpos($source, '\');
$result = substr($source, $pos === FALSE ? 0 : $pos);