Resolve a relative path in a URL with PHP

前端 未结 2 1911
独厮守ぢ
独厮守ぢ 2021-01-13 22:49

Example 1: domain.com/dir_1/dir_2/dir_3/./../../../
Should resolve naturally in the browser into = domain.com/

Example 2: domain.c

2条回答
  •  灰色年华
    2021-01-13 23:34

    This is a more simple problem then you are thinking about it. All you need to do is explode() on the / character, and parse out all of the individual segments using a stack. As you traverse the array from left to right, if you see ., do nothing. If you see .., pop an element from the stack. Otherwise, push an element onto the stack.

    $str = 'domain.com/dir_1/dir_2/dir_3/./../../../';
    $array = explode( '/', $str);
    $domain = array_shift( $array);
    
    $parents = array();
    foreach( $array as $dir) {
        switch( $dir) {
            case '.':
            // Don't need to do anything here
            break;
            case '..':
                array_pop( $parents);
            break;
            default:
                $parents[] = $dir;
            break;
        }
    }
    
    echo $domain . '/' . implode( '/', $parents);
    

    This will properly resolve the URLs in all of your test cases.

    Note that error checking is left as an exercise to the user (i.e. when the $parents stack is empty and you try to pop something off of it).

提交回复
热议问题