3

コードを見てみましょう

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

質問 1. dirname を 2 回使用して 2 レベル上に移動するのはエレガントですか?

質問 2. 3 レベル上に行きたい場合、dirname を 3 回使用することをお勧めしますか?

4

2 に答える 2

1

質問 1. dirname を 2 回使用して 2 レベル上に移動するのはエレガントですか?

私はそれがエレガントだとは思いませんが、同時に2つのレベルでおそらく問題ありません

質問 2. 3 レベル上に行きたい場合、dirname を 3 回使用することをお勧めしますか?

レベルが高くなるほど、読みにくくなります。多数のレベルで 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_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
于 2014-07-16T14:21:29.087 に答える