问题
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
回答1:
realpath($path);
Docs
回答2:
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.
来源:https://stackoverflow.com/questions/2338912/is-there-an-inbuilt-way-in-php-to-parse-a-string-like-this-path-to-up-s