Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Trailing Slash From String PHP

Tags:

string

php

People also ask

How to remove trailing slash in php?

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.

How remove forward and backward slash from string in PHP?

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8"; $access_token = preg_replace('/\\\//', '/', $access_token);

How do I get rid of trailing slash 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.


Sure it is, simply check if the last character is a slash and then nuke that one.

if(substr($string, -1) == '/') {
    $string = substr($string, 0, -1);
}

Another (probably better) option would be using rtrim() - this one removes all trailing slashes:

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

This removes trailing slashes:

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

Long accepted, however in my related searches I stumbled here, and am adding for "completeness"; rtrim() is great, however implemented like this:

$string = rtrim($string, '/\\'); //strip both forward and back slashes

It ensures portability from *nix to Windows, as I assume this question pertains to dealing with paths.


rtrim Use rtrim cause it respects the string doesnt end with a trailing slash