如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:54:53  来源:igfitidea点击:

How to get a platform independent directory separator in PHP?

phpdirectoryfilepath

提问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 $someDirectoryand $someFileare 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", "/");

http://php.net/manual/en/function.php-uname.php

http://php.net/manual/en/function.php-uname.php