2013-06-23 68 views
4

一个URL的一部分,我有以下PHP变量PHP,删除变量

$currentUrl 

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

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

我可以使用什么PHP代码将以此为URL链接,并删除“的.html”后,一切会回到我一个干净的URL链接,例如:

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

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

+0

http://php.net/manual/en/function.parse-url.php – hjpotter92

回答

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); 
+0

谢谢鲁本的代码,它确实会返回一个干净的网址,但它也增加了一些其他的东西。这是它使用你的代码返回的内容:“Array([0] => example.com/test-category/page.html)” – RaduS

+0

我怎样才能让它返回干净的“http://example.com/test-类别/ page.html中?”没有“阵列([0] =>”在乞讨和没有“)”在最后 – RaduS

+0

print_r只是为了告诉你结果。你可以通过使用$ matches [0]来实际获取结果:echo $ matches [0]; – Ruben

1
$parts = explode('?', $currentUrl); 
$url = $parts[0]; 
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 
) 
*/ 
?> 

然后你就可以从价值建立你想要的网址。

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

你sugestion也工作得很好。谢谢您的回答 – RaduS

+6

这应该是被接受的答案。这是工作的正确工具。 – TecBrat

+2

嗨TecBrat,的确,这也是正确的答案,我希望我可以接受他们都是正确的。为了不同的目的,我将使用parse_url()和preg_match。重要的想法是,我了解了这两种解决方案 – RaduS