code-8
code-8

Reputation: 58662

Replace value of specific URL param in PHP

I have a Facebook link string:

"https://www.facebook.com/v2.5/dialog/oauth?client_id=*****&state=*****&response_type=code&sdk=php-sdk-5.1.2&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Ffacebook%2Flink&scope=email%2Cuser_birthday%2Cuser_photos"

I want to replace:

redirect_uri=http%3A%2F%2Flocalhost%3A8888

to

redirect_uri=http%3A%2F%2Flocalhost


I would do something like this if it's the browser URL, but it is a string inside a anchor tag.

if (isset($_GET['redirect_uri'])) {
    echo $_GET['redirect_uri'];
}else{
    // Fallback behaviour goes here
}

How do I do something like that?


I've tried

$permissions = 'user_birthday,user_photos';
$login_url = $fb->getLoginUrl(['email','scope'=>$permissions]);
$urls = explode("&", $login_url);
$redirect_uri = explode("=", $urls[4]);
$link = explode("%2F", $redirect_uri[1]);

dd($link);

// array:5 [▼
//   0 => "http%3A"
//   1 => ""
//   2 => "localhost%3A8888" // I want to replace this string with 'localhost'
//   3 => "facebook"
//   4 => "link"
// ]

Upvotes: 0

Views: 3297

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

Considering this input string:

https://www.facebook.com/v2.5/dialog/oauth?client_id=*****&state=*****&response_type=code&sdk=php-sdk-5.1.2&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Ffacebook%2Flink&scope=email%2Cuser_birthday%2Cuser_photos

You can use this flexible regex pattern with an empty replacement string:

/&redirect_uri=\S+?localhost\K%[^%]+/

Replacement Demo Link

This pattern (in plain terms) says:

  • match "&redirect_uri="
  • match any non-white-character one or more times (stopping as soon as possible)
  • match "localhost"
  • restart the "full string match" (\K)
  • match "%"
  • match one or more non-% characters

Upvotes: 1

marcellorvalle
marcellorvalle

Reputation: 1679

Maybe some regex replacement?

$url = 'https://www.facebook.com/v2.5/dialog/oauth?client_id=*****&state=*****&response_type=code&sdk=php-sdk-5.1.2&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Ffacebook%2Flink&scope=email%2Cuser_birthday%2Cuser_photos';

$pattern = '/redirect_uri=http\%3A\%2F\%2F[\%0-9A-Za-z]+facebook/';
$replace = 'redirect_uri=http%3A%2F%2Flocalhost%2Ffacebook';
$newURl = preg_replace($pattern, $replace, $url);

Upvotes: 2

Adam
Adam

Reputation: 1304

If your string is actually redirect_uri=http%3A%2F%2Flocalhost%3A8888 then do this:

$url = $_GET['redirect_uri'];
$url = str_replace('redirect_uri=http%3A%2F%2Flocalhost%3A8888', 'redirect_uri=http%3A%2F%2Flocalhost', $url);

This will search the string and make the required changes, then save it back to the $url variable.

Obviously, you could use $_GET['redirect_uri'], either way you should sanitise the input:

Filter Input

Filters - Sanitise

See also: http://php.net/manual/en/function.str-replace.php

Upvotes: 1

Related Questions