PHP: a good way to universalize paths in the OS (slash)

My simple problem is to handle paths through the OS, mainly regarding backslash and forward slashes for directory separators.

I used DIRECTORY_SEPARATOR , however:

  • Write long

  • Paths can come from different sources, not necessarily controlled by you

I am currently using:

  function pth($path) { $runningOnWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'); $slash = $runningOnWindows ? '\\' : '/'; $wrongSlash = $runningOnWindows ? '/' : '\\' ; return (str_replace($wrongSlash, $slash, $path)); } 

I just want to know that in the language I invent, there is nothing

Is there any built-in PHP functionality for this?

+7
source share
4 answers

I know DIRECTORY_SEPARATOR,

However: 1. Long write

Laziness is never a reason for anything

 $path = (DIRECTORY_SEPARATOR === '\\') ? str_replace('/', '\\', $subject) : str_replace('\\', '/', $subject); 

or

 $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); 

This will replace the β€œright” one in one step, but it does not matter.

If you know for sure that a path exists, you can use realpath ()

 $path = realpath($path); 

However, this is not required at all, since each OS understands that the forward slash / is a valid directory separator (even windows).

+26
source

You are not given the predefined constant DIRECTORY_SEPARATOR .

+4
source

If you are going to pass these paths to the standard PHP functions, I think you don't need to fix the paths as far as I can tell. Basic functions, such as file_get_contents or fopen , work great with any type of path that you throw at them.

+1
source
  static function fx_slsh($path) { $path = str_replace(['/','\\'], DIRECTORY_SEPARATOR, $path); return substr($path, -1) == DIRECTORY_SEPARATOR ? $path : $path . DIRECTORY_SEPARATOR; } 

it also ensures that there is an end slash

0
source

All Articles