[英]Get only the filename from a path
我有这串
$string = 'C:\Folder\Sub-Folder\file.ext';
我想将其更改为:
$string = 'file.ext';
使用PHP,我试图编写一种忽略最后\\
剩下的所有内容的方法。
使用basename()
与str_replace()
为\\
路径不被认可的basename()
$filename = basename(str_replace('\\', '/', 'C:\Folder\Sub-Foler\file.ext'));
echo $filename; // file.ext
另一个解决方案是这样的:
用分隔符( \\
)分割字符串以形成数组: ['C:', 'Folder', 'Sub-Foler', 'file.ext']
使用explode
: explode("\\\\", $string);
使用end
函数获取数组中的最后一个元素,作为结果。
放在一起:
$string = 'C:\Folder\Sub-Foler\file.ext';
$stringPieces = explode("\\", $string);
$string = end($stringPieces);
这是一个演示:http: //3v4l.org/i1du4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.