Search code examples
phpurlrelative-path

How to get URL relative "deepness"?


In PHP, how would I get the URL relative indicators based on where I'm located? Examples:

Location                 Return

example.com              ./
example.com/sub          ../
example.com/sub/sub      ../../

...

Solution

  • Considering your above example:

    $url = 'example.com/sub/sub/';
    $parts = explode('/', $url);
    $parts = array_filter($parts, 'strlen');
    $path = count($parts) == 1 ? './' : str_repeat('../', count($parts)-1);
    

    This code ignores the empty parts and trailing slashes (e.g.: example.com//sub/).