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

时间:2014-07-16 09:55:07

标签: php dirname

看一下代码

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

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

问题2.如果你想提高三级,那么使用dirname三次是一个好习惯吗?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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

结果是:

{{1}}