Uuid
Uuid

Reputation: 2546

How do I get the query string of a URL (the parts after the question mark)?

How can I get only the content from a query string staring from ?:

asegment?param1=value1&param2=value2

NOTE: I only need all the content after the "?", also I want to ommit that character.

Upvotes: 1

Views: 1875

Answers (6)

Orangepill
Orangepill

Reputation: 24645

You have a couple of options before that dont require regex like

$val = (strpos("?", $url) !== false? substr($url, strpos($url, "?")): "");

or parse_url

$val = parse_url($url, PHP_URL_QUERY);

EDIT

Fixed condtition where there is not query string

Upvotes: 1

oroshnivskyy
oroshnivskyy

Reputation: 1579

You should use $_GET global array <?php echo $_GET["param1"]; ?>

Upvotes: 0

brbcoding
brbcoding

Reputation: 13596

This is a simple solution using strrev and strtok...

$url = "asegment?param1=value1&param2=value2";
echo strrev(strtok(strrev($url),'?'));

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Here is the Regex \?(.+), and a Rubular to prove it. And to use it:

preg_match("/\?(.+)/", $inputString, $matches);
if (!$matches) {
    // no matches
}

$result = $matches[1];

Upvotes: 2

SubSevn
SubSevn

Reputation: 1028

\?([a-z0-9A-z&=]+)*

This looks like you're dealing with URLs, consider a library designed for them. And if you're only interested in getting everything after the ?, then use something like

String s = "asegment?param1=value1&param2=value2";
String paramStr = s.substring(s.indexOf('?')-1);

Edit: Didn't see that you were using PHP - disregard.

Upvotes: 1

halfer
halfer

Reputation: 20429

If you are sure your string has a query in it, then this will do the trick:

echo substr( $string, strpos( $string, '?' ) + 1 );

If your string may not contain the query, then check first - strpos will return boolean false.

Upvotes: 3

Related Questions