Remove Trailing Slash from String PHP

Remove Trailing Slash From String PHP

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, '/');

Find trailing slash and delete all after it then delete slash

You can get position of the last slash by strrpos() method and then you just remove the string after that position by substr_replace()

like,

$url = "https://db.ygoprodeck.com/card/Qliphort%20Shell/?_ga=2.211230173.973474856.1550500277-1234167223.1550500277";
echo $new = substr_replace($url,'',strrpos($url, '/'));

Thank you.

Removing a forward-slash from the tail-end of an URL

$site = preg_replace('{/$}', '', $site);

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

Remove first occurance of trailing slash in php

You can use the ltrim function as:

$result = ltrim( ltrim($dir['subdir']), '/');

The inner ltrim removes leading whitespace and the outer ltrim removes the / as you want it.



Related Topics



Leave a reply



Submit