使用 PHP 在 URL 中删除尾部斜杠的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2392677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to remove trailing slashes in URLs with PHP
提问by daniel
I have some URLs, like www.amazon.com/, www.digg.comor www.microsoft.com/and I want to remove the trailing slash, if it exists, so not just the last character. Is there a trimor rtrimfor this?
我有一些 URL,例如www.amazon.com/, www.digg.comorwww.microsoft.com/并且我想删除尾部斜杠(如果存在),所以不仅仅是最后一个字符。是否有一个trim或rtrim这个?
回答by Erik
You put rtrimin your answer, why not just look it up?
你rtrim输入你的答案,为什么不查一下呢?
$url = rtrim($url,"/");
As a side note, look up any PHP function by doing the following:
作为旁注,通过执行以下操作查找任何 PHP 函数:
(rtrimstands for 'Right trim')
(rtrim代表“正确修剪”)
回答by Dario Fumagalli
Simple and works across both Windows and Unix:
简单且适用于 Windows 和 Unix:
$url = rtrim($url, '/\')
回答by Kenneth Kaane
I came here looking for a way to remove trailing slash and redirect the browser, I have come up with an answer that I would like to share for anyone coming after me:
我来这里是为了寻找一种删除尾部斜杠和重定向浏览器的方法,我想出了一个答案,我想与任何追随我的人分享:
//remove trailing slash from uri
if( ($_SERVER['REQUEST_URI'] != "/") and preg_match('{/$}',$_SERVER['REQUEST_URI']) ) {
header ('Location: '.preg_replace('{/$}', '', $_SERVER['REQUEST_URI']));
exit();
}
The ($_SERVER['REQUEST_URI'] != "/")will avoid host URI e.g www.amazon.com/ because web browsers always send a trailing slash after a domain name, and preg_match('{/$}',$_SERVER['REQUEST_URI'])will match all other URI with trailing slash as last character. Then preg_replace('{/$}', '', $_SERVER['REQUEST_URI'])will remove the slash and hand over to header()to redirect. The exit()function is important to stop any further code execution.
该($_SERVER['REQUEST_URI'] != "/")会避免主机URI如www.amazon.com/因为Web浏览器总是一个域名后发送斜线,并preg_match('{/$}',$_SERVER['REQUEST_URI'])会匹配所有其它的URI以斜线作为最后一个字符。然后preg_replace('{/$}', '', $_SERVER['REQUEST_URI'])将删除斜杠并移交header()给重定向。该exit()函数对于停止任何进一步的代码执行很重要。
回答by ghostdog74
$urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
echo preg_replace("/\b\//","",$urls);

