PHP How to remove last part of a path

后端 未结 5 1955
太阳男子
太阳男子 2020-12-01 17:51

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:

pare

相关标签:
5条回答
  • 2020-12-01 18:22

    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'))
    0 讨论(0)
  • 2020-12-01 18:22

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 18:28
        preg_replace("/\/\w+$/i","",__DIR__);
         # Note you may also need to add .DIRECTORY_SEPARATOR at the end.
    
    0 讨论(0)
  • 2020-12-01 18:34
    dirname($path)
    

    And this is the documentation.

    0 讨论(0)
  • 2020-12-01 18:44

    dirname()

    0 讨论(0)
提交回复
热议问题