How to get only a piece of an URL? (php)

Go To StackoverFlow.com

1

I have this url:

example.com/?do=search&q=testing+this+out

I need to store the part after &q= in a variable.

What PHP function would be the best for doing that, explode, slice?

P.S. I use $request_url = $_SERVER['REQUEST_URI']; to get the URI.

2012-04-04 21:39
by Gerben
you want parse_url() http://www.php.net/manual/en/function.parse-url.ph - Cfreak 2012-04-04 21:42
Why not $_GET["q"];Ben 2012-04-04 21:42


5

If you just need the value of q, you can simply write:

$value = $_GET['q'];
2012-04-04 21:41
by Aurelio De Rosa
I think OP has a string containing the url and wants to decompose that, not an actual url for the currently executing script - Marc B 2012-04-04 21:43
@MarcB I don't think so, read the P.S - Ben 2012-04-04 21:43
@ben: d'oh... I think I need to get a few weeks' worth of sleep.. - Marc B 2012-04-04 21:44


4

There's parse_url() to slice 'n dice a url into its components, then parse_str() will take a query string and decompose it into a regular key-value array.

$url = 'your url here';
$parts = parse_url($url);
$query = parse_str($parts['query']);
echo $query['q'];
2012-04-04 21:42
by Marc B


0

I don't understand why $_GET is not sufficient. But incase it isn't, here:

$ php -r '$url = "http://example.com/?do=search&q=testing+this+out"; $parts = parse_url($url); $vars = explode("&", $parts["query"]); print_r($vars);'
Array
(
    [0] => do=search
    [1] => q=testing+this+out
)
2012-04-04 21:43
by vicTROLLA


0

mabye more quick and more simple...

$requested_query_vars = $_SERVER["QUERY_STRING"];

or parse_url() php function

$requested_query_vars = parse_url($request_url, PHP_URL_QUERY); 
2012-04-04 21:58
by Tribalpixel
Ads