PHP How to remove last part of a path
I have a path like this:
parent/child/reply
How do I 开发者_运维知识库use PHP to remove the last part of the path, so that it looks like this:
parent/child
dirname($path)
And this is the documentation.
dirname()
. You can use it as many times as you'd like
- to get parent/child - dirname('parent/child/reply')
- to get parent - dirname(dirname('parent/child/reply'))
dirname()
preg_replace("/\/\w+$/i","",__DIR__);
# Note you may also need to add .DIRECTORY_SEPARATOR at the end.
Here' is a function to remove the last n part of a URL:
/**
* 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;
}
More simple, if you have a path like
$path="/p1/p2/.../pN"
you can use 'dirname()' function as
echo dirname($path,L)
where 'L' is the level to up. For L=1, is the current folder, L=2 is the '../pN-1', for L=3 we have "../pN-2" e so on ...
For sample, is your path is '$path="/etc/php/7.4/apache2/"'
, and L=2, so
echo dirname($path,2)
will output
/etc/php/7.4/
for L=3
/etc/php
Thats it.
精彩评论