Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP equivalent function to the Python os.path.normpath()?

Tags:

python

path

php

Is there a PHP equivalent function to the Python os.path.normpath()?
Or how can i get the exactly same functionality in PHP?

like image 947
troex Avatar asked Apr 19 '10 19:04

troex


People also ask

What is os path Normpath?

path. normpath() method in Python is used to normalize the specified path.

What does path () do in Python?

dirname(path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name.

How do I get the path of a directory in Python?

dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.


2 Answers

Here is my 1:1 rewrite of normpath() method from Python's 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 exactly the same as os.path.normpath() in Python

like image 114
troex Avatar answered Oct 10 '22 01:10

troex


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

However, it will also resolve symbolic links. I'm not sure what you'd do if you didn't want that behavior.

like image 28
Powerlord Avatar answered Oct 10 '22 02:10

Powerlord