How to Remove a Trailing Slash From a PHP String?

In PHP, you can remove a trailing slash from a string in the following ways:

Using rtrim()

You can specify the "/" character as the second the argument to the rtrim() function to remove one or more trailing slashes, for example, like so:

$url = 'https://www.designcise.com/';
echo rtrim($url, '/'); // 'https://www.designcise.com'

The rtrim() function matches and removes multiple occurrences of the "/" character:

$url = 'https://www.designcise.com///';
echo rtrim($url, '/'); // 'https://www.designcise.com'

Using a Regular Expression

You can use a regular expression with the preg_replace() function to remove a trailing slash without the need to first explicitly check if a trailing slash exists and then remove it. For example:

$url = 'https://www.designcise.com/';
echo preg_replace('/\/$/', '', $url); // 'https://www.designcise.com'

The above pattern would only only match and replace a single occurrence of "/" at the end of the string. However, you can update the pattern to remove multiple occurrences as well, for example, like so:

$url = 'https://www.designcise.com///';
echo preg_replace('/\/*$/', '', $url); // 'https://www.designcise.com'

Checking the End Character and Removing Accordingly

You can use the following function to remove a single occurrence of the "/" character:

function rtrimOnce(string $str): string
{
    $substrLen = strlen($str) - 1;
    return substr($str, 0, $substrLen);
}

// ...

Prior to calling this function though, you need to check if the end character is indeed a forward slash (/). To do so, you can do any of the following:

// ...
$url = 'https://www.designcise.com/';
echo ($url !== '' && $url[-1] === '/') ? rtrimOnce($url) : $url;

// output: 'https://www.designcise.com'
// PHP 8+
// ...
$url = 'https://www.designcise.com/';
echo (str_ends_with($url, '/')) ? rtrimOnce($url) : $url;

// output: 'https://www.designcise.com'
// ...
$url = 'https://www.designcise.com/';
echo (substr($url, -1) === '/') ? rtrimOnce($url) : $url;

// output: 'https://www.designcise.com'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.