1

I was trying to use a regular expression to get the value of the code parameter of the following url:

"http:\/\/instagram.com\/?code=wz6kmXaZbrDCHU8OdOW0PrshbZF60Zz8Aji4ivaG"

Unfortunately it didn't work out so I had ended up doing the following:

$jsonRedirectUriWithAuthCode = "http:\/\/instagram.com\/?code=wz6kmXaZbrDCHU8OdOW0PrshbZF60Zz8Aji4ivaG";

print "jsonRedirectUriWithAuthCode= " . $jsonRedirectUriWithAuthCode;
print "\n";
$query = parse_url($jsonRedirectUriWithAuthCode, PHP_URL_QUERY);
print "query= " . $query;
print "\n";
parse_str($query, $params);
print "params['code']= ". $params['code'];
die() ;

Which outputs:

jsonRedirectUriWithAuthCode= "http:\/\/instagram.com\/?code=wz6kmXaZbrDCHU8OdOW0PrshbZF60Zz8Aji4ivaG"
query= code=wz6kmXaZbrDCHU8OdOW0PrshbZF60Zz8Aji4ivaG"
params['code']= wz6kmXaZbrDCHU8OdOW0PrshbZF60Zz8Aji4ivaG"

The above does what I wanted to. But I'm still curious how this would be done if using a regular expression. Could someone maybe show me how to extract the value of the code parameter with a regular expression?

Cœur
  • 37,241
  • 25
  • 195
  • 267
superkytoz
  • 1,267
  • 4
  • 23
  • 43
  • 1
    Using `parse_url` and `parse_str` is the way to go, there's no reason to use a regex here *(except if you want to introduce errors)*. – Casimir et Hippolyte Dec 29 '16 at 22:32
  • Any practical use, or just curiosity? – Alex Blex Dec 29 '16 at 22:32
  • @AlexBlex curiosity :) – superkytoz Dec 29 '16 at 22:35
  • 1
    `[&?]code=\K[[:alnum:]]+` does the job, but it may fail when an url contains for example a password like that : `http://username:"&code=toto"@domain.com/path/file.php?code=abcd1234` *(`parse_url` avoids this kind of problems)*. – Casimir et Hippolyte Dec 29 '16 at 22:39
  • Would be quite tricky for arbitrary value, but with some assumptions (e.g. code value is always base64 encoded) could be fairly simple. – Alex Blex Dec 29 '16 at 22:42
  • go with `parse_url` and `parse_str`, to satisfy your curiosity, you can use something like: `preg_match_all('/code=(.*?)$/', $theurl, $matches); echo $matches[1][0];` – Pedro Lobito Dec 29 '16 at 23:00
  • Possible duplicate of [Extract URL parameters with regex - repeating a capture group](http://stackoverflow.com/questions/7762626/extract-url-parameters-with-regex-repeating-a-capture-group) –  Dec 29 '16 at 23:58

1 Answers1

1

Go with parse_url and parse_str. To satisfy your curiosity, you can use something like:

preg_match_all('/code=(.*?)$/', $theUrl, $match); 
echo $match[1][0];
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268