If you're looking to be more flexible in how many levels up you would like to go, then I would suggest writing a small function to help take care of this for you.
Here's an example piece of code which might do what you would like. Instead of using dirname
multiple times or calling a for
loop, it uses preg_split, array_slice, and implode, assuming that /
is your directory separator.
$string = 'http://example.com/some_folder/another_folder/yet_another/folder/file
.txt';
for ($i = 0; $i < 5; $i++) {
print "$i levels up: " . get_dir_path($string, $i) . "\n";
}
function get_dir_path($path_to_file, $levels_up=0) {
// Remove the http(s) protocol header
$path_to_file = preg_replace('/https?:\/\//', '', $path_to_file);
// Remove the file basename since we only care about path info.
$directory_path = dirname($path_to_file);
$directories = preg_split('/\//', $directory_path);
$levels_to_include = sizeof($directories) - $levels_up;
$directories_to_return = array_slice($directories, 0, $levels_to_include);
return implode($directories_to_return, '/');
}
The result is:
0 levels up: example.com/some_folder/another_folder/yet_another/folder
1 levels up: example.com/some_folder/another_folder/yet_another
2 levels up: example.com/some_folder/another_folder
3 levels up: example.com/some_folder
4 levels up: example.com