How to get parameters from a URL string?

前端 未结 13 1452
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:36

    As mentioned in other answer, best solution is using

    parse_url()

    You need to use combination of parse_url() and parse_str().

    The parse_url() parse URL and return its components that you can get query string using query key. Then you should use parse_str() that parse query string and return values into variable.

    $url = "https://example.com/test/1234?basic=2&email=xyz2@test.com";
    parse_str(parse_url($url)['query'], $params);
    echo $params['email']; // xyz2@test.com
    

    Also you can do this work using regex.

    preg_match()

    You can use preg_match() to get specific value of query string from URL.

    preg_match("/&?email=([^&]+)/", $url, $matches);
    echo $matches[1]; // xyz2@test.com
    

    preg_replace()

    Also you can use preg_replace() to do this work in one line!

    $email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
    // xyz2@test.com
    

提交回复
热议问题