PHP网址问题

sta*_*cks 2 php

有没有办法我可以使用PHP从链接中删除变量,例如,如果我有一个链接,读取http://localhost/link/index.php?s=30&p=3我将如何删除?s=30&p=3所以我的链接读取http://localhost/link/index.php

sve*_*ens 10

list($url) = explode("?", $longUrl, 2);
Run Code Online (Sandbox Code Playgroud)


Pet*_*tai 6

编辑(由Hoohah建议):

你也可以使用strstr()(PHP 5.3.0以后):

echo strstr($longurl, "?", TRUE);
Run Code Online (Sandbox Code Playgroud)

PHP具有内置功能.

它是parse_url().看一下可能的返回值.在这种情况下,我们可以使用scheme,hostpath.

例如:

<?php
$info = parse_url("http://localhost/link/index.php?s=30&p=3");
echo $info["scheme"] . "://" . $info["host"] . $info["path"];
  // Output: http://localhost/link/index.php
?>
Run Code Online (Sandbox Code Playgroud)

实例


此方法优于使用的优点explode()是,它可以控制您是否要显示用户名,密码和端口(如果包含).上面的代码不会显示任何这些,所以http://user:pass@localhost:81/link/index.php?s=30&p=3将返回http://localhost/link/index.php,删除用户名,密码和端口号,这是我认为你想要的.用户名,密码和端口可为$info["user"],$info["pass"]$info["port"].

explode()如果密码包含问号,则方法失败.即使使用?@登录密码,此方法也不会失败.


最后要注意的是,如果您要处理端口号,用户名和密码,可以使用下面的代码(有一行添加的行)来删除用户名和密码,但保留端口号:

<?php      
$info = parse_url("http://user:__?**@@@@&?ss@localhost:80/link/index.php?s=30&p=3");
  // If port is present add a colon before it, if not make it an empty string.
isset($info["port"]) ? $port = ":" . $info["port"] : $port ="";
echo $info["scheme"] . "://" . $info["host"] . $port . $info["path"];
  // Outputs: http://localhost:80/link/index.php
?>
Run Code Online (Sandbox Code Playgroud)

实例


最后,你真的不应该在链接中使用用户名和密码.来自RFC2396

某些URL方案在userinfo字段中使用"user:password"格式.不推荐这种做法,因为在几乎所有使用它的情况下,以明文(例如URI)传递认证信息已被证明是一种安全风险.