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
dirname(). You can use it as many times as you'd like
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;
}
preg_replace("/\/\w+$/i","",__DIR__);
# Note you may also need to add .DIRECTORY_SEPARATOR at the end.
dirname($path)
And this is the documentation.
dirname()