Summary of php Method for Obtaining url Parameters

  • 2021-08-03 09:20:56
  • OfStack

In this paper, the method of obtaining url parameters by php is described as an example. Share it for your reference. The details are as follows:

There are many ways to get parameters in url in php, among which the simplest one is to use parse_url function directly, which can automatically analyze url parameters and values conveniently and quickly and save them to the corresponding array. The other one is basically operated by regular expressions.

parse_url function
Let's first understand the parse_url function under 1, and the official solution

Description:
mixed parse_url ( string $url [, int $component = -1 ] )

This function parses an URL and returns an associative array containing the various components that appear in an URL.
This function is not used to verify the validity of a given URL, but to break it down into the parts listed below. Incomplete URL is also accepted, and parse_url () will try to parse it as correctly as possible.
The URL to parse. Invalid characters will be replaced with _.

Examples are as follows:

$url = "https://www.ofstack.com/welcome/";
$parts = parse_url($url);
print_r($parts); array
(
    [scheme] => http
    [host] => www.ofstack.com
    [path] => /welcome/
)

You can also write an algorithm yourself! As follows
function getParams() 
{
   $url = '/index.php?_p=index&_a=show&x=12&y=23';
  
   $refer_url = parse_url($url);
  
   $params = $refer_url['query'];
  
   $arr = array();
   if(!empty($params))
   {
       $paramsArr = explode('&',$params);
  
       foreach($paramsArr as $k=>$v)
       {
          $a = explode('=',$v);
          $arr[$a[0]] = $a[1];
       }
   }
   return $arr;
}

Invoke method
$arr = getParams(); 
print_r($arr);

The running results are as follows:

Array ( [_p] => index [_a] => show [x] => 12 [y] => 23 )

I hope this article is helpful to everyone's PHP programming.


Related articles: