我有一个像这样的路径:
parent/child/reply
parent/child
dirname()
函数可以被多次使用
preg_replace("/\/\w+$/i","",__DIR__);
# Note you may also need to add .DIRECTORY_SEPARATOR at the end.
/**
* 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;
}
$path="/p1/p2/.../pN"
echo dirname($path,L)
其中'L'代表要上升的层级。当L=1时,代表当前文件夹,L=2时是'../pN-1',当L=3时是'../pN-2'等等...
举个例子,如果你的路径是'$path="/etc/php/7.4/apache2/"'
,而L=2,则
echo dirname($path,2)
/etc/php/7.4/
对于 L=3
/etc/php
就是这样。
dirname
的for
循环呢?太简单了吗? - lxg