PHP - preg_replace 删除斜线和之后

PHP - preg_replace remove slash and after

好吧,我想删除域名后的斜杠和 url 的其余部分。在这段代码中:

$url = $_POST['url'];
$result = preg_replace('#/[^/]*$#', '', $url);
echo $result;

它将删除斜杠和它后面的 (/index.php),但只有当 URL 是这样的时候:

http://site.domain/index.php

但是在这个:

http://site.domain/index/test

或更多斜杠,它只会删除最后一个斜杠和尾部 (/test)。

我想删除域名后的第一个斜线:

示例:

http://site.domain/index/test/test/test/test/test/test

删除:

/index/test/test/test/test/test/test

结果:

http://site.domain

我不知道如何定义域和路径后的第一个斜杠。 第二个问题是 url 是:

http://test.domain

它会删除 /test.com 但我从来不想要这个,我想要当 url 域名后没有任何斜杠时它不要从 http:// 中删除第二个斜杠!好吧,我知道我应该定义删除域后的第一个斜杠,或者换句话说,删除路径中的第一个斜杠或 php self.

怎么样:

$result = preg_replace('#((?:https?://)?[^/]*)(?:/.*)?$#', '', $url);

这将保留第一个斜杠之前的所有内容(如果存在,则在 http:// 之后)

$result = preg_replace('%((https?://)?.*?)/.*$%', '', $url);

解释:

((https?://)?.*?)/.*$


Match the regex below and capture its match into backreference number 1 «((https?://)?.*?)»
   Match the regex below and capture its match into backreference number 2 «(https?://)?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Match the character string “http” literally «http»
      Match the character “s” literally «s?»
         Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Match the character string “://” literally «://»
   Match any single character that is NOT a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “/” literally «/»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»



Insert the text that was last matched by capturing group number 1 «»

您使用了错误的工具。这是函数 parse_url() 的作业。使用它将 URL 解析为组件(方案、用户+密码、主机+端口、路径、查询字符串、片段),然后选择您需要的部分并将它们放在一起以获得您想要的 URL .

$url = $_POST['url'];

// Parse the URL into pieces
$pieces = parse_url($url);

// Put some of the pieces back together to get a new URL
// Scheme ('http://' or 'https://')
$newUrl = $pieces['scheme'].'://';
// Username + password, if present
if (! empty($pieces['user'])) {
    $newUrl .= $pieces['user'];
    if (! empty($pieces['pass'])) {
        $newUrl .= ':'.$pieces['pass'];
    }
    $newUrl .= '@';
}
// Hostname
$newUrl .= $pieces['host'];
// Port, if present
if (! empty($pieces['port'])) {
    $newUrl .= ':'.$pieces['port'];
}

// That't all. Ignore path, query string and url fragment
echo($newUrl);

附带说明一下,组合部分可以使用函数 http_build_url(); unfortunately, this function is provided by the HTTP extension which is not bundled with PHP 轻松完成。它必须单独安装,这意味着如果代码不托管在您自己的服务器上,它很可能不可用。