Parse URL in php

后端 未结 2 1521
小鲜肉
小鲜肉 2021-01-28 08:33

In php, if I wanted to parse a URL, such as www.site.com/index.php?foo=bar, I can do with the _POST variable. I can retrieve bar by _POST[\'foo\'].

2条回答
  •  失恋的感觉
    2021-01-28 09:10

    Use parse_url.

    Quoted from php.net:

    This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

    This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

    Then, use parse_str function to parse the query parameters part.

    Parses str as if it were the query string passed via a URL and sets variables in the current scope. To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources. The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

     www.site.com/index.php [query] => foo&bar )
    
    
      parse_str ($parts['query'], $query);
      print_r($query);
      // Array ( [foo] => [bar] => ) 
    
     // Alternately you can do this in a single shot like below:
     parse_str(parse_url('www.site.com/index.php?foo&bar', PHP_URL_QUERY));
    
    ?>
    

提交回复
热议问题