[ACCEPTED]-Removing a forward-slash from the tail-end of an URL-php

Accepted answer
Score: 47

You can pass a string of characters that 3 you want trimmed off of a string to the 2 trim family of functions. Also, you could use 1 rtrim to trim just the end of the string:

$site = rtrim($site, "/");
Score: 25
$site = preg_replace('{/$}', '', $site);

This uses a relatively simple regular expression. The $ means 5 only match slashes at the end of the string, so 4 it won't remove the first slash in stackoverflow.com/questions/. The 3 curly braces {} are just delimiters; PHP requires 2 matching characters and the front and back 1 of regular expressions, for some silly reason.

Score: 8

Simplest method:

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

0

Score: 3

John was the first and I think his solution 5 should be preferred, because it's way more 4 elegant, however here is another one:

$site = implode("/", array_filter(explode("/", $site)));

Update

Thx. I 3 updated it and now even handles things like 2 this

$site = "///test///test//"; /* to => test/test */

Which probably makes it even cooler 1 than the accepted answer ;)

Score: 2

Is that what You want?

$url = 'http://www.example.com/';

if (substr($url, -1) == '/')
    $url = substr($url, 0, -1);

0

Score: 1

You could have a slash before the question 9 mark sign and you could have the "?" sign 8 or "/" in the parameters (.com/?price=1), so 7 you shouldn't delete this every time. You 6 need to delete only the first slash "/" before 5 the question mark "?" or delete 4 the last slash "/" if you have 3 no question marks "?" at all.

For 2 example:

https://money.yandex.ru/to/410011131033942/?&question=where?&word=why?&back_url=https://money.yandex.ru/to/410011131033942/&price=1

would be

https://money.yandex.ru/to/410011131033942?&question=where?&word=why?&back_url=https://money.yandex.ru/to/410011131033942/&price=1

And

https://money.yandex.ru/to/410011131033942/

would be

https://money.yandex.ru/to/410011131033942

The PHP code 1 for this would be:

if(stripos($url, '?')) {
    $url = preg_replace('{/\?}', '?', $url);
} else {
    $url = preg_replace('{/$}', '', $url);
}
Score: 0

The most elegant solution is to use rtrim().

$url = 'http://www.domain.com/';

$urlWithoutTrailingSlash = rtrim($url, '/');

EDIT

I forgot 2 about rtrim();

You could also play around 1 parse_url().

More Related questions