[英]Get only the filename from a path
I have this string 我有这串
$string = 'C:\Folder\Sub-Folder\file.ext';
I want to change it to: 我想将其更改为:
$string = 'file.ext';
Using PHP, I am trying to write a method that ignores everything left of the last \\
. 使用PHP,我试图编写一种忽略最后
\\
剩下的所有内容的方法。
Use basename()
with str_replace()
as the \\
in the path is not recognized by basename()
使用
basename()
与str_replace()
为\\
路径不被认可的basename()
$filename = basename(str_replace('\\', '/', 'C:\Folder\Sub-Foler\file.ext'));
echo $filename; // file.ext
Another solution is this: 另一个解决方案是这样的:
Split the string by a delimiter( \\
) to form an array: ['C:', 'Folder', 'Sub-Foler', 'file.ext']
using explode
: explode("\\\\", $string);
用分隔符(
\\
)分割字符串以形成数组: ['C:', 'Folder', 'Sub-Foler', 'file.ext']
使用explode
: explode("\\\\", $string);
Get the last element in the array using the end
function, which you want as the result. 使用
end
函数获取数组中的最后一个元素,作为结果。
Put it all together: 放在一起:
$string = 'C:\Folder\Sub-Foler\file.ext';
$stringPieces = explode("\\", $string);
$string = end($stringPieces);
Here's a demo: http://3v4l.org/i1du4 这是一个演示:http: //3v4l.org/i1du4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.