Is there an equivalent PHP function for Python os.path.normpath ()?

Is there an equivalent PHP function for Python os.path.normpath() ?
Or how can I get exactly the same functionality in PHP?

+6
python php path
source share
2 answers

Here is my 1: 1 rewriting of the normpath () method from Python posixpath.py in PHP:

 function normpath($path) { if (empty($path)) return '.'; if (strpos($path, '/') === 0) $initial_slashes = true; else $initial_slashes = false; if ( ($initial_slashes) && (strpos($path, '//') === 0) && (strpos($path, '///') === false) ) $initial_slashes = 2; $initial_slashes = (int) $initial_slashes; $comps = explode('/', $path); $new_comps = array(); foreach ($comps as $comp) { if (in_array($comp, array('', '.'))) continue; if ( ($comp != '..') || (!$initial_slashes && !$new_comps) || ($new_comps && (end($new_comps) == '..')) ) array_push($new_comps, $comp); elseif ($new_comps) array_pop($new_comps); } $comps = $new_comps; $path = implode('/', $comps); if ($initial_slashes) $path = str_repeat('/', $initial_slashes) . $path; if ($path) return $path; else return '.'; } 

This will work just like os.path.normpath () in Python

+6
source share

Yes, the realpath command will return a normalized path. This is similar to the combined version of Python os.path.normpath and os.path.realpath .

However, it will also allow symbolic links. I'm not sure what you would do if you did not want this behavior.

+2
source share

All Articles