Reputation: 33551
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
Upvotes: 31
Views: 28505
Reputation: 1816
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.
Upvotes: 2
Reputation: 31090
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;
}
Upvotes: 2
Reputation: 31
preg_replace("/\/\w+$/i","",__DIR__);
# Note you may also need to add .DIRECTORY_SEPARATOR at the end.
Upvotes: 3
Reputation: 963
dirname()
. You can use it as many times as you'd like
Upvotes: 28