php PHP如何删除路径的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2430208/
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 06:27:04 来源:igfitidea点击:
PHP How to remove last part of a path
提问by Mark
I have a path like this:
我有这样的路径:
parent/child/reply
parent/child/reply
How do I use PHP to remove the last part of the path, so that it looks like this:
如何使用 PHP 删除路径的最后一部分,使其看起来像这样:
parent/child
parent/child
Thanks!
谢谢!
回答by zneak
回答by Ivan Peevski
回答by Bill
preg_replace("/\/\w+$/i","",__DIR__);
# Note you may also need to add .DIRECTORY_SEPARATOR at the end.
回答by Mahmoud Zalt
Here' is a function to remove the last npart of a URL:
这是一个删除URL后n部分的函数:
/**
* remove the last `$level` of directories from a path
* example 'aaa/bbb/ccc' remove 2 levels will return aaa/
*
* @param $path
* @param $level
*
* @return mixed
*/
public function removeLastDir($path, $level)
{
if (is_int($level) && $level > 0) {
$path = preg_replace('#\/[^/]*$#', '', $path);
return $this->removeLastDir($path, (int)$level - 1);
}
return $path;
}

