How to get parameters from a URL string?

前端 未结 13 1455
孤城傲影
孤城傲影 2020-11-22 04:05

I have a HTML form field $_POST[\"url\"] having some URL strings as the value. Example values are:

https://example.com/test/1234?email=xyz@test.com
         


        
13条回答
  •  盖世英雄少女心
    2020-11-22 04:41

    Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don't like polluting the current context, so providing a second parameter puts all the variables into an associative array.

    $url = "https://mysite.com/test/1234?email=xyz4@test.com&testin=123";
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    print_r($query_params);
    
    //Output: Array ( [email] => xyz4@test.com [testin] => 123 ) 
    

提交回复
热议问题