[英]PHP: remove filename from path
Say I have an path: images/alphabet/abc/23345.jpg假设我有一条路径:images/alphabet/abc/23345.jpg
How do I remove the file at the end from the path?如何从路径末尾删除文件? So I end up with: images/aphabet/abc/
所以我最终得到:images/aphabet/abc/
<?php
$path = pathinfo('images/alphabet/abc/23345.jpg');
echo $path['dirname'];
?>
http://php.net/manual/en/function.pathinfo.php http://php.net/manual/en/function.pathinfo.php
dirname()
only gives you the parent folder's name , sodirname()
will fail wherepathinfo()
will not .dirname()
只为您提供父文件夹的名称,因此dirname()
将在pathinfo()
不会失败的地方失败。
For that, you should use pathinfo()
:为此,您应该使用
pathinfo()
:
$dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME);
The PATHINFO_DIRNAME
tells pathinfo
to directly return the dirname
. PATHINFO_DIRNAME
告诉pathinfo
直接返回dirname
。
See some examples:看一些例子:
For path images/alphabet/abc/23345.jpg
, both works:对于路径
images/alphabet/abc/23345.jpg
,两者都有效:
<?php $dirname = dirname('images/alphabet/abc/23345.jpg'); // $dirname === 'images/alphabet/abc/' $dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'
For path images/alphabet/abc/
, where dirname
fails:对于路径
images/alphabet/abc/
,其中dirname
失败:
<?php $dirname = dirname('images/alphabet/abc/'); // $dirname === 'images/alphabet/' $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'
Note that when a string contains only a filename without a path (eg "test.txt"
), the dirname()
and pathinfo()
functions return a single dot ( "."
) as a directory, instead of an empty string.请注意,当字符串仅包含没有路径的文件名时(例如
"test.txt"
), dirname()
和pathinfo()
函数返回一个点 ( "."
) 作为目录,而不是空字符串。 And if your string ends with "/"
, ie when a string contains only path without filename, these functions ignore this ending slash and return you a parent directory.如果您的字符串以
"/"
结尾,即当字符串仅包含没有文件名的路径时,这些函数将忽略此结尾斜杠并返回父目录。 In some cases this may be undesirable behavior and you need to use something else.在某些情况下,这可能是不受欢迎的行为,您需要使用其他东西。 For example, if your path may contain only forward slashes
"/"
, ie only one variant (not both slash "/"
and backslash "\"
) then you can use this function:例如,如果您的路径可能只包含正斜杠
"/"
,即只有一个变体(不是斜杠"/"
和反斜杠"\"
),那么您可以使用这个 function:
function stripFileName(string $path): string
{
if (($pos = strrpos($path, '/')) !== false) {
return substr($path, 0, $pos);
} else {
return '';
}
}
Or the same thing little shorter, but less clear:或者同样的东西更短,但不太清楚:
function stripFileName(string $path): string
{
return substr($path, 0, (int) strrpos($path, '/'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.