How to remove the last character from a string in PHP

Updated Sep 22, 2023 ⤳ 5 min read

How do you remove the last character from a string in PHP? Most web developers face it at one time or another; It can be a white space, a trailing slash in a HTTP URL, the last comma in a comma-separated list, or even a new line character (\n).

Luckily, in PHP, removing the last character from string is easy enough.

In this quick guide, we’ll try three ways of removing the last character(s) from a string in PHP.

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

24/7 lofi music radio banner, showing a young man working at his computer on a rainy autmn night with hot drink on the desk.

Let’s begin with my favorite option: the rtrim function, a.k.a the right trim.

Remove the last character by PHP rtrim()

PHP rtrim() accepts two arguments: the input string and characters you wish to be stripped from the end of the input string.

For instance, to remove the last comma in a comma-separated list:


<?php

$var = 'Banana, apple, orange, ';
$trimmed = rtrim($var, ', ');

var_dump($trimmed);

// output: string(21) "Banana, apple, orange"

Let's see a more realistic example; A common use case of removing the last character from a string is to remove the trailing slash in a URL.

Imagine you have a function that accepts a URL prefix as an argument. This function adds a path (e.g., /api/v2) to the prefix and returns the result.


<?php

function getApiUrl($baseUrl) 
{
    return $baseUrl . '/api/v2';
}

$apiUrl = getApiUrl('https://decodingweb.dev/');
var_dump($apiUrl);

// output: string(31) "https://decodingweb.dev//api/v2"

The problem with the above approach is that if the $baseUrl contains a trailing slash, you might end up with double slashes in the final URL.

You can simply avoid double slashes with rtrim() like so:


<?php

function getApiUrl($baseUrl) 
{
    return rtrim($baseUrl, '/') . '/api/v2';
}

$apiUrl = getApiUrl('https://decodingweb.dev/');
var_dump($apiUrl);

// output: string(31) https://decodingweb.dev/api/v2

But what if you needed to remove a number of characters from the end of the string (regardless of what they are)? Please read on.

Remove the last character by PHP substr()

One way to strip the last character in a string is by using the PHP substr() function.

substr() function returns a portion of a string based on an offset and length (number of characters).


<?php

$var = 'abcdef';
$trimmed = substr($var, 0, 2);

var_dump($trimmed);

// output: string(2) "ab"

In the above example, the offset is 0 (the first character), and the length is 2, which is the number of characters counting from the offset.

And the result is ab.

The offset can also take a negative value! When the offset is negative, the count will begin from the end of the string. Saying that -1 means the last character from the end of the string. The value -2 means the last two characters, and so forth.

That sounds like what we need! Let's see an example.


<?php

$baseUrl = 'http://decodingweb.dev/';

var_dump(substr($baseUrl, 0, -1));

// output:  string(22) "http://decodingweb.dev"

And if you want to remove the last three characters from a string:


<?php

$string = 'abcdf';
$trimmed = substr($string, 0, -3)

var_dump($trimmed);

// output: string(2) "ab"

Or even remove the last five characters from the string:


<?php

$string = 'abcdf';
$trimmed = substr($string, 0, -5)

var_dump($trimmed);

// output: string(0) 

The above example will return an empty string.

You can also use substr() to check the last character in a string, like so:


<?php

$string = 'abcdf';

var_dump(substr($string, -1, 1));

// output: string(1) f

How about the multi-byte characters? Each character in English takes one byte. However, many UTF-8 characters take more than one byte (multi-byte characters). For instance, accents over characters such as ä, é, or even an emoji 🍏 takes more than a byte.

The offset and length in substr() function won't handle multi-byte characters as expected because they assume one byte per character.

Let's see it in an example:


<?php

$var = 'Cartão de Crédito';
$trimmed = substr($var, 2, 6);

var_dump($trimmed);

// output: string(21) string(6) "rtão "

In the above example, the offset 2 and length 6 is supposed to return rtão d. However, the returned value is rtão . The reason is ã is a multi-byte character, and substr() function isn't aware of it!

Luckily, PHP has a multi-byte safe substr() alternative: mb_substr():


<?php

$var = 'Cartão de Crédito';
$trimmed = mb_substr($var, 2, 6);

var_dump($trimmed);

// output: string(7) "rtão d"

Remove the last character by PHP substr_replace()

Another method to remove the last character from a string in PHP is by using the substr_replace() function. 

You can use substr_replace() to replace string values with a replacement value.


<?php

$var = 'This is a test';
$newVar = substr_replace($var, 'that', 0, 4);

var_dump($newVar);

// output: string(14) "that is a test"

In the above example, offset 0 and length 4 refers to "This" in our string. And in this case, "This" is replaced with the word "That".

As a result, the output would be: "That is a test".

Now, what if we can target the last character and replace it with an empty string?

We can! Let's see how:


<?php

$baseUrl = 'http://decodingweb.dev/';

var_dump(substr_replace($baseUrl, '', -1));

// output:  string(22) http://decodingweb.dev

We set the offset to -1 (the last character) and replaced it with an empty string (''). Just like that!

Wrapping up

PHP is great at string manipulation, thanks to the functions we can use from the standard library.

I hope this quick guide gave you the answer you were looking for.

Thanks for reading.

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`