PHP How to remove last part of a path

后端 未结 5 1973
太阳男子
太阳男子 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

    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;
    }
    

提交回复
热议问题