【问题标题】:Get only the filename from a path仅从路径中获取文件名
【发布时间】:2015-06-04 17:04:48
【问题描述】:

我有这个字符串

$string = 'C:\Folder\Sub-Folder\file.ext';

我想改成:

$string = 'file.ext';

使用 PHP,我正在尝试编写一个忽略最后一个 \ 剩下的所有内容的方法。

【问题讨论】:

标签: php string filenames


【解决方案1】:

使用basename()str_replace() 作为路径\ 中的is not recognized by basename()

$filename = basename(str_replace('\\', '/', 'C:\Folder\Sub-Foler\file.ext'));
echo $filename; // file.ext

Demo

【讨论】:

  • 是的,就是这样!谢谢兄弟。
  • 在这里是正确的,它确实识别反斜杠,但仅在 Windows 上 :) 正如我所说的 RTM xD
【解决方案2】:

另一个解决方案是这样的:

用分隔符(\)将字符串分割成一个数组:['C:', 'Folder', 'Sub-Foler', 'file.ext'] 使用explodeexplode("\\", $string);

使用 end 函数获取数组中的最后一个元素,这是您想要的结果。

把它们放在一起:

$string = 'C:\Folder\Sub-Foler\file.ext';
$stringPieces = explode("\\", $string);
$string = end($stringPieces);

这是一个演示:http://3v4l.org/i1du4

【讨论】:

    猜你喜欢
    • 2011-11-16
    • 2012-01-21
    • 2012-10-25
    • 1970-01-01
    • 2023-03-26
    • 2015-04-22
    • 2014-07-24
    • 1970-01-01
    相关资源
    最近更新 更多