如何在 PHP 中获得独立于平台的目录分隔符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6654157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a platform independent directory separator in PHP?
提问by retrodrone
I'm building a path string in PHP. I need it to work across platforms (i.e., Linux, Windows, OS X). I'm doing this:
我正在用 PHP 构建一个路径字符串。我需要它跨平台(即 Linux、Windows、OS X)工作。我这样做:
$path = $someDirectory.'/'.$someFile;
Assume $someDirectory
and $someFile
are formatted correctly at run-time on the various platforms. This works beautifully on Linux and OS X, but not on Windows. The issue is the /
character, which I thought would work for Windows.
假设$someDirectory
和$someFile
在运行时在各种平台上正确格式化。这在 Linux 和 OS X 上工作得很好,但在 Windows 上不工作。问题是/
字符,我认为它适用于 Windows。
Is there a PHP function or some other trick to switch this to \
at runtime on Windows?
是否有 PHP 函数或其他一些技巧可以\
在 Windows 上运行时切换到它?
EDIT:Just to be clear, the resultant string is
编辑:为了清楚起见,结果字符串是
c:\Program Files (x86)\Sitefusion\Sitefusion.org\Defaults\pref/user.preferences
on Windows. Obviously the mix of slashes confuses Windows.
在 Windows 上。显然,斜线的混合混淆了 Windows。
回答by genesis
Try this one
试试这个
DIRECTORY_SEPARATOR
DIRECTORY_SEPARATOR
$patch = $somePath. DIRECTORY_SEPARATOR .$someFile
or you can define yours
或者你可以定义你的
PHP_OS == "Windows" ||
PHP_OS == "WINNT" ? define("SEPARATOR", "\") : define("SEPARATOR", "/");
回答by Maxim Mikhisor
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
define("SEPARATOR", "\");
else
define("SEPARATOR", "/");