Remove the last character from a string in PHP
In this tutorial, you will learn how to remove the last character from a string in php. Here we explain to you three methods to do this task.
Remove the last character from a string in PHP, Delete the last character of a string, rtrim function, substr_replace function, substr function, Remove last comma from the string. get last character of string php, remove unwanted characters from string php, remove last character from string javascript.
Checkout more articles on JavaScript
- Remove Duplicate Values from an Array in JavaScript
- Convert an Array to String in JavaScript
- Compare two dates in JavaScript
- Convert a String to a Number in JavaScript
Different way to remove the last character from a string
Method 1: rtrim function
Using the `rtrim` function, we can remove the last specific characters from the string. By default this function removes whitespace from the end of string.
Syntax:
rtrim($string, 'x');
Example:
$string = "Welcome to Cluemediator !";
echo $string . "\n";
$newString = rtrim($string, "!");
echo $newString . "\n";
// Output:
Welcome to Cluemediator !
Welcome to Cluemediator
In some cases, the `rtrim` function will not work for us because it removes all specific characters from the end of string. Let's be clear with an example.
$string = "This is a test message..";
echo $string . "\n";
$newString = rtrim($string,".");
echo $newString . "\n";
// Output:
This is a test message..
This is a test message
Here, if we want to remove only single `.` character from the end of the string but rtrim function removes all `.` characters. In this case we can use the `substr` function or `substr_replace` function of php.
Method 2: substr function
We can use the `substr` function to remove last characters from the string.
Syntax:
substr($string, 0, -1);
Example:
$string = "Welcome to Cluemediator !";
echo $string . "\n";
$newString = substr($string, 0, -1);
echo $newString . "\n";
// Output:
Welcome to Cluemediator !
Welcome to Cluemediator
Another example where you can see its remove only one character if more than one same characters are available at the end of string and want to remove only one of them last character.
$string = "This is a test message..";
echo $string . "\n";
$newString = substr($string, 0, -1);
echo $newString . "\n";
// Output:
This is a test message..
This is a test message.
Method 3: substr_replace function
Also, you can use the `substr_replace` function to remove the last character from a string.
Syntax:
substr_replace($string, "", -1);
Example:
$string = "Welcome to Cluemediator !";
echo $string . "\n";
$newString = substr_replace($string, "", -1);
echo $newString . "\n";
// Output:
Welcome to Cluemediator !
Welcome to Cluemediator
That’s it for today.
Thank you for the reading. Happy Coding!