Mark
Mark

Reputation: 33551

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

Upvotes: 31

Views: 28505

Answers (6)

albert
albert

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

Mahmoud Zalt
Mahmoud Zalt

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

Bill
Bill

Reputation: 31

    preg_replace("/\/\w+$/i","",__DIR__);
     # Note you may also need to add .DIRECTORY_SEPARATOR at the end.

Upvotes: 3

Ivan Peevski
Ivan Peevski

Reputation: 963

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'))

Upvotes: 28

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

dirname()

Upvotes: 7

zneak
zneak

Reputation: 138031

dirname($path)

And this is the documentation.

Upvotes: 76

Related Questions