如何在PHP中加入文件系统路径字符串? [英] How to join filesystem path strings in PHP?

查看:154
本文介绍了如何在PHP中加入文件系统路径字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有内置函数可以智能地连接路径字符串?给定函数"abc/de/"和"/fg/x.php"的函数应返回"abc/de/fg/x.php";应该使用"abc/de"和"fg/x.php"作为该函数的参数来给出相同的结果.

Is there a builtin function in PHP to intelligently join path strings? The function, given "abc/de/" and "/fg/x.php" as arguments, should return "abc/de/fg/x.php"; the same result should be given using "abc/de" and "fg/x.php" as arguments for that function.

如果没有,是否有可用的课程?这对于拆分路径或删除其中的一部分可能也很有价值.如果您写过什么,可以在这里分享您的代码吗?

If not, is there an available class? It could also be valuable for splitting paths or removing parts of them. If you have written something, may you share your code here?

始终使用"/"是可以的,我仅针对Linux进行编码.

It is ok to always use "/", I am coding for Linux only.

在Python中有os.path.join(),这很棒.

In Python there is os.path.join(), which is great.

推荐答案

由于这似乎是一个很受欢迎的问题,并且注释中充斥着功能建议"或错误报告" ...此代码段所做的只是将两个带有斜杠的字符串连接在一起,而不必在它们之间重复斜杠.就这样.不多不少.它不评估硬盘上的实际路径,也不实际保留起始斜杠(如果需要,可以添加斜杠,至少可以确保此代码始终返回不带斜杠的字符串 ).

join('/', array(trim("abc/de/", '/'), trim("/fg/x.php", '/')));

最终结果将始终是在开头或结尾没有斜杠且在其中没有双斜杠的路径.随意使用它.

The end result will always be a path with no slashes at the beginning or end and no double slashes within. Feel free to make a function out of that.

这是上面片段的一个很好的灵活函数包装器.您可以根据需要传递任意数量的路径摘要,可以是数组,也可以是单独的参数:

Here's a nice flexible function wrapper for above snippet. You can pass as many path snippets as you want, either as array or separate arguments:

function joinPaths() {
    $args = func_get_args();
    $paths = array();
    foreach ($args as $arg) {
        $paths = array_merge($paths, (array)$arg);
    }

    $paths = array_map(create_function('$p', 'return trim($p, "/");'), $paths);
    $paths = array_filter($paths);
    return join('/', $paths);
}

echo joinPaths(array('my/path', 'is', '/an/array'));
//or
echo joinPaths('my/paths/', '/are/', 'a/r/g/u/m/e/n/t/s/');

:o)

这篇关于如何在PHP中加入文件系统路径字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆