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,cWhy 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)