How to remove the last character from a string in PHP
Tags: php, webdev, beginners
Published: 2023-02-06 19:36:21

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/php-remove-last-character-from-string) for a 💯 user experience. _~reza_

How do you remove the last character from a string in PHP? Most [web developers](https://www.decodingweb.dev/how-to-become-a-web-developer) 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 characters (`\n`).

Luckily, PHP has plenty of string manipulation functions you can use to get rid of that last character. 

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

Let’s begin with my favorite option `rtrim()` 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
<?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 reason to remove 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 URL prefix and returns the result.

```php
<?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 result.

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

```php
<?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.

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

```php
<?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
<?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
<?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
<?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
<?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, called 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
<?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
<?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. 

Just like `substr()`, this function accepts a `position` and `offset` too. However, unlike `substr()` - which returns a substring - `substr_replace()` replaces the substring with a replacement value.

Let's make it clear with an example:

```php
<?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
<?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

As you see, 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.