PHP,删除URL变量的一部分

4

我有以下的PHP变量

$currentUrl

这个PHP变量会返回当前页面的URL。例如:它会返回:

http://example.com/test-category/page.html?_ore=norn&___frore=norian

我可以使用哪些php代码来删除链接中“.html”后面的所有内容,并返回一个干净的链接,例如:

http://example.com/test-category/page.html

这将在一个新变量 $clean_currentUrl 中返回。


http://php.net/manual/en/function.parse-url.php - hjpotter92
3个回答

13
通过PHP的parse_url()函数。
<?php 
$url = "http://example.com/test-category/page.html?_ore=norn&___frore=norian";
$url = parse_url($url);

print_r($url);
/*
Array
(
    [scheme] => http
    [host] => example.com
    [path] => /test-category/page.html
    [query] => _ore=norn&___frore=norian
)
*/
?>

然后您可以从这些值构建您所需的URL。

$clean_url = $url['scheme'].'://'.$url['host'].$url['path'];

你的建议也非常有效。感谢你的回答。 - RaduS
6
这应该是被认可的答案。这是正确的工具来完成这项工作。 - TecBrat
2
嗨TecBrat,没错,这也是正确的答案,我希望能够将它们都接受为正确的答案。我将使用parse_url()和preg_match来实现不同的目的。重要的是我学到了这两种解决方案。 - RaduS
我正在使用"parse_url($currentUrl2, PHP_URL_PATH);"它返回给我"example.com/test-category/page.html",我该如何让它也加上"http://",这样它就会返回给我"http://example.com/test-category/page.html"。 - RaduS
仅回答我的上面的问题,这是解决方案:"$clean_url = parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST).parse_url($url, PHP_URL_PATH);" - RaduS
@RaduS 检查一下我的答案的最后一部分,你不需要多次使用parse_url()函数,因为该函数返回一个数组,然后你可以使用数组值来构建你的 $clean_url - Lawrence Cherone

1
像这样的东西:
<?php
$currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian';

preg_match('~http:\/\/.*\.html~', $currentUrl, $matches);
print_r($matches);

请参考下面amigura的评论。为了处理这种情况,请更改正则表达式:
<?php
$currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian';

preg_match('~(http:\/\/.*\..+)\?~', $currentUrl, $matches);
print_r($matches);

感谢Ruben提供的代码,它确实返回了一个干净的URL,但也添加了一些其他内容。这是使用您的代码返回的内容:“Array([0] => example.com/test-category/page.html)”。 - RaduS
如何使其返回一个干净的“http://example.com/test-category/page.html?”而不是以“Array([0] =>”开头,也不要以“)”结尾。 - RaduS
Array(...) 是 print_r 函数的输出,它展示数据的方式。 - Ruben
@amigura 好的,很公平,我修改了答案来处理这个问题。 :) - Ruben
各位,请不要为正确答案争论不休。我很感激能够了解到两者的区别。 - RaduS
显示剩余6条评论

1
$parts = explode('?', $currentUrl);
$url = $parts[0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接