views:

60

answers:

2

So say I have a string like so of a path

$path = '/path/to/../../up/something.txt';

Is there a way built into PHP to parse it and come up with a URL without the directory ups (../) ?

E.g.

$path = parsePath('/path/to/../../up/something.txt'); // /up/something.txt
+6  A: 
realpath($path);

Docs

alex
Man I love PHP.
echo
As long as $path corresponds to an actual filesystem path that you have read permissions on. It won't do the job with just any arbitrary path-like thing (but then again there are reasons for that).
hobbs
@Hobbs, that is worth noting. I found that out myself when trying to do it with an arbitrary string. http://stackoverflow.com/questions/2338935/why-would-this-string-be-returning-false-in-php-when-realpathd
alex
@echo I have to say I can *almost* forgive PHP's untidiness and inconsistencies for the amount of cool built in stuff :)
alex
A: 

PHP's realpath() is cool, but what if you want to figure it out without accessing the filesystem?

I've written this function that can return a path with ../ and the like calculated to a real path.

It probably doesn't handle all path commands, so let me know if you think I should implement another.

public function resolvePath($path) {

    while (strstr($path, '../')) {
        $path = preg_replace('/\w+\/\.\.\//', '', $path);
    }

    return $path;

}

The regex I borrowed from this user contributed note.

alex