How to Remove the Last Character of a String in PHP


If you need to remove the last character of a string in PHP, then you can do the following:

Option 1 – Using rtrim()

Syntax: rtrim($string, $character)

$mystring = "This is a PHP program!";
echo("Before Removal: $mystring\n");
# Before Removal: This is a PHP program!

$newstring = rtrim($mystring, ". ");
echo("After Removal: $newstring");
# After Removal: This is a PHP program

Option 2 – Using substr()

Syntax: substr($string, $start, $length)

$mystring = "This is a PHP program!";
echo substr($mystring, 0, -1);
# This is a PHP program