Is there an inbuilt way in PHP to parse a string like this: '/path/to/../../up/something.txt'

痴心易碎 提交于 2019-12-22 10:34:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!