14

here's my code snippet to start with:

$url = $_SERVER["REQUEST_URI"]; // gives /test/test/ from http://example.org/test/test/
echo"$url"; 
trim ( $url ,'/' );
echo"$url";

I use this in combination with .htaccess rewrite, I’ll get the information from the URL and generate the page for the user with PHP using explode. I don't want .htaccess to interpret the URL, which is probably better, but I am more common with PHP and I think it’s more flexible.

I already read this (which basically is what I want): Best way to remove trailing slashes in URLs with PHP

The only problem is, that trim doesn’t trim the leading slashes. Why? But actually it should work. Replacing '/' with "/", '\47' or '\x2F' doesn’t change anything. It neither works online nor on localhost. What am I doing wrong?

Community
  • 1
  • 1
someonelse
  • 260
  • 1
  • 3
  • 13

4 Answers4

31

The trim function returns the trimmed string. It doesn't modify the original. Your third line should be:

$url = trim($url, '/');
Tesserex
  • 17,166
  • 5
  • 66
  • 106
4

This can be done in one line...

echo trim($_SERVER['REQUEST_URI'], '/');
Sirko
  • 72,589
  • 19
  • 149
  • 183
Ace
  • 41
  • 1
2

You need to do:

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

You also should just do

echo $url;

It is faster.

Alec Gorge
  • 17,110
  • 10
  • 59
  • 71
1

trim does not modify the original. You'll need to do something such as:

$url = $_SERVER["REQUEST_URI"]; // gives /test/test/ from http://example.org/test/test/
echo"$url"; 
$url = trim ( $url ,'/' );
echo"$url";
erisco
  • 14,154
  • 2
  • 40
  • 45