Best way to remove trailing slashes in URLs with PHP

Php

Php Problem Overview


I have some URLs, like www.amazon.com/, www.digg.com or www.microsoft.com/ and I want to remove the trailing slash, if it exists, so not just the last character. Is there a trim or rtrim for this?

Php Solutions


Solution 1 - Php

You put rtrim in your answer, why not just look it up?

$url = rtrim($url,"/");

As a side note, look up any PHP function by doing the following:

(rtrim stands for 'Right trim')

Solution 2 - Php

Simple and works across both Windows and Unix:

$url = rtrim($url, '/\\')

Solution 3 - Php

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.

Solution 4 - Php

$urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
echo preg_replace("/\b\//","",$urls);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanielView Question on Stackoverflow
Solution 1 - PhpErikView Answer on Stackoverflow
Solution 2 - PhpDario FumagalliView Answer on Stackoverflow
Solution 3 - PhpKenneth KaaneView Answer on Stackoverflow
Solution 4 - Phpghostdog74View Answer on Stackoverflow