好吧,我想在域名后删除斜杠和其余的url。在这段代码中:
$url = $_POST['url'];
$result = preg_replace('#/[^/]*$#', '', $url);
echo $result;
它会删除斜杠并在它之后(/index.php),但只有当URL是这样的时候:
但在此:
或更多斜杠它只会删除最后一个斜杠和轨迹(/ test)。
我想删除域后的第一个斜杠:
示例:
卸下:
/索引/测试/检验/测试/检验/测试/检验
结果:
我不知道如何在域和路径之后定义第一个斜杠。 第二个问题是网址是:
它将删除/test.com但我从来不想要这个,我想当url在域名之后没有任何斜杠它不要从http://删除第二个斜杠!好吧,我知道我应该定义在域之后删除第一个斜杠或者在路径或php self中删除第一个斜杠。
答案 0 :(得分:3)
怎么样:
$result = preg_replace('#((?:https?://)?[^/]*)(?:/.*)?$#', '$1', $url);
这将锁定第一个斜杠之前的所有内容(在http:// if present之后)
答案 1 :(得分:0)
$result = preg_replace('%((https?://)?.*?)/.*$%', '$1', $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 «$»
$1
Insert the text that was last matched by capturing group number 1 «$1»
答案 2 :(得分:0)
您使用的是错误的工具。这是函数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()轻松完成组合部分;遗憾的是,此功能由HTTP extension not bundled with PHP提供。它必须单独安装,这意味着如果代码不在您自己的服务器上托管,则很可能无法使用。