Lets say my URL is:
http://www.example.com/news/media-centre/news/17/an-example-news-post/?foo=bar
I want to in PHP remove the last directory in the URL so I get:
How do I do this while making sure I maintain any other URL parameters?
I've tried using this:
$url = parse_url( $url );
$url['path'] = str_replace( strrchr($url['path'], "/"), "", $url['path'] );
But the replace would cause issues if the last directory is also somewhere else in the path too.
Not to mention stitching the URL back together seems like a long way round...
$url = "http://www.example.com/news/media-centre/news/17/an-example-news-post/?foo=bar";
$info = parse_url($url);
$info["path"]=dirname($info["path"]);
$new_url = $info["proto"]."://".$info["host"].$info["path"];
if(!empty($info["query"])) $new_url .= "?".$info["query"];
if(!empty($info["fragment"])) $new_url .= "#".$info["fragment"];