Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim slashes from Request_Uri

Tags:

url

php

uri

trim

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?

like image 893
someonelse Avatar asked Feb 27 '11 19:02

someonelse


People also ask

How do I remove the last slash from a URL in WordPress?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash. Likewise, if it is not present there, the slash will be missing in your website's URLs.

How do I remove the last slash from a URL in Java?

replaceAll("/","");

How remove forward and backward slash from string in PHP?

The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.


2 Answers

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

$url = trim($url, '/');
like image 98
Tesserex Avatar answered Oct 13 '22 00:10

Tesserex


This can be done in one line...

echo trim($_SERVER['REQUEST_URI'], '/');
like image 21
Ace Avatar answered Oct 12 '22 23:10

Ace