3

看一下代码

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

问题 1. 两次使用 dirname 上两级是否优雅?

问题 2. 如果您想上三个级别,那么使用 dirname 三次是否是一个好习惯?

4

2 回答 2

1

问题 1. 两次使用 dirname 上两级是否优雅?

我不认为它很优雅,但同时它可能适合 2 个级别

问题 2. 如果您想上三个级别,那么使用 dirname 三次是否是一个好习惯?

您拥有的级别越多,它的可读性就越低。对于大量级别,我会使用 foreach,如果它经常使用,那么我会将它放在一个函数中

function multiple_dirname($path, $number_of_levels) {

    foreach(range(1, $number_of_levels) as $i) {
        $path = dirname($path);
    }

    return $path;
}
于 2014-07-16T10:10:39.950 回答
1

如果您希望在想要升级多少级别时更加灵活,那么我建议您编写一个小函数来帮助您解决这个问题。

这是一个示例代码,它可能会执行您想要的操作。它不是使用dirname多次或调用for循环,而是使用preg_splitarray_sliceimplode,假设这/是您的目录分隔符。

$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
于 2014-07-16T14:21:29.087 回答