How to get everything after the domain name into a string

前端 未结 2 1643
花落未央
花落未央 2020-12-21 01:39

My goal is to get everything after the domain name into a string. As in mysite.com/page/page2 would result in a string \"page/page2\". That I can do, however it starts givin

相关标签:
2条回答
  • 2020-12-21 01:48

    You could use $_SERVER['REQUEST_URI'] and then modify the string with PHP's substr() function. So, put the URI into a variable and then run that function to remove the first X number of characters (domain name length) from the beginning and X number of characters from the end (index.php = 9).

    For example:

    $new_url = substr($uri_variable, 10, -9);

    Where $uri_variable is the $_SERVER[REQUEST_URI']`, 10 is the character after the domain name and -9 is the characters in index.php.

    https://www.php.net/manual/en/reserved.variables.server.php http://php.net/manual/en/function.substr.php

    0 讨论(0)
    • get the path by parsing the request uri
    • remove eventual script name from the end of the string (e.g. index.php)
    • rtrim any trailing slashes

      $request = parse_url($_SERVER['REQUEST_URI']);
      $path = $request["path"];
      $result = rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
      

    EDIT

    $request = parse_url($_SERVER['REQUEST_URI']);
    $path = $request["path"];
    
    $result = trim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
    
    $result = explode('/', $result);
    $max_level = 2;
    while ($max_level < count($result)) {
        unset($result[0]);
    }
    $result = '/'.implode('/', $result);
    
    0 讨论(0)
提交回复
热议问题