Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove the last character from a string

Short answer

mb_substr() with a negative length of -1 returns the string without its last character:

<?php
 
$text = 'Привет!';
 
echo mb_substr($text, 0, -1);

Output:

Привет

Removing a specific trailing character

To drop, say, a trailing comma, rtrim() is more convenient. It removes all of the given characters from the end, not just one:

<?php
 
echo rtrim('a,b,c,,', ',');

Output:

a,b,c

Why not substr()

substr() works on bytes. A Cyrillic letter takes two bytes, so the function cuts off only half of it and leaves a broken character in the string:

<?php
 
var_dump(mb_check_encoding(substr('Привет', 0, -1), 'UTF-8'));
var_dump(mb_check_encoding(mb_substr('Привет', 0, -1), 'UTF-8'));

Output:

bool(false)
bool(true)

Functions used in this recipe

  • mb_substr — Returns part of a string.
  • trim — Removes whitespace and other characters from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.