使用dirname访问两个或三个文件夹两次或三次



看一下代码

$link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo dirname(dirname($link));

问题1。使用两次dirname来提升两层是不是很优雅?

问题2。如果您想要再上三层,那么使用dirname三次是不是一个好的做法?

如果你想在你想去的多少级别上更灵活,那么我建议写一个小函数来帮助照顾你。

下面是一段示例代码,它可能会做你想做的事情。它没有多次使用dirname或调用for循环,而是使用preg_split、array_slice和implode,假设/是您的目录分隔符。

$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, '/');
}

结果是:

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

问题1。使用两次dirname来提升两层是不是很优雅?

我不认为它是优雅的,但同时它可能是好的两个级别

问题2。如果你想上三层的话,这是一个很好的练习使用dirname三次?

关卡越多,可读性越差。对于大量的级别,我会使用foreach,如果它经常使用,那么我会将其放在函数

中。
function multiple_dirname($path, $number_of_levels) {
    foreach(range(1, $number_of_levels) as $i) {
        $path = dirname($path);
    }
    return $path;
}

最新更新