How do I extract query parameters from a URL string in PHP?

后端 未结 3 901
时光取名叫无心
时光取名叫无心 2020-11-28 14:28

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to

3条回答
  •  甜味超标
    2020-11-28 15:02

    You can use parse_url and parse_str like this:

    $query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
    parse_str($query, $params);
    $test = $params['test'];
    

    parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.

提交回复
热议问题