替换PHP中特定URL参数的值

时间:2016-03-29 19:27:29

标签: php url substring str-replace

我有一个Facebook链接字符串:

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

我想替换:

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

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

如果它是浏览器URL,我会这样做,但它是一个锚标签内的字符串。

$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"
// ]

我该怎么做?

我试过

.loading{
  color:black;
  position:fixed;
  width: 270px;
  height:100px;
  font-size:20px;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  transition: 1s ease-out;
  opacity:1;
}



  .loading:after {
    overflow: hidden;
    display: inline-block;
    vertical-align: bottom;
    animation: ellipsis steps(4,end) 900ms infinite;
    content: "\2026"; /* ascii code for the ellipsis character */
    width: 0px;
  }

  @keyframes ellipsis {
    to {
      width: 20px;
    }
  }

  @-webkit-keyframes ellipsis {
    to {
      width: 20px;
    }
  }


.centered{
  vertical-align:middle;
  text-align:center;
  align-items: center;
  justify-content: center;
}

3 个答案:

答案 0 :(得分:2)

也许有一些正则表达式替换?

$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);

答案 1 :(得分:1)

如果您的字符串实际上是redirect_uri=http%3A%2F%2Flocalhost%3A8888,请执行以下操作:

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

这将搜索字符串并进行所需的更改,然后将其保存回$url变量。

显然,您可以使用$_GET['redirect_uri'],无论哪种方式都应该清理输入:

Filter Input

Filters - Sanitise

另请参阅:http://php.net/manual/en/function.str-replace.php

答案 2 :(得分:1)

考虑此输入字符串:

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

您可以将此灵活的正则表达式模式与空替换字符串一起使用:

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

Replacement Demo Link

这种模式(简单来说)说:

  • 匹配“& redirect_uri =”
  • 匹配任何非白色字符一次或多次(尽快停止)
  • 匹配“localhost”
  • 重新启动“完整字符串匹配”(\K
  • 匹配“%”
  • 匹配一个或多个非%字符