
How to Remove the Last Character from a String in PHP
Introduction
In PHP, you often work with string data — and sometimes, you just need to remove the last character. Whether you're trimming off an extra comma, cutting the last digit from a phone number, or removing a newline character, PHP offers multiple tools for this task. In this tutorial, you'll learn how to do it cleanly, safely, and efficiently.
Why Would You Want to Remove the Last Character?
There are many real-world scenarios where trimming the final character becomes essential:
- You want to strip the last comma from a CSV list
- You accidentally added an extra symbol or letter at the end
- Your string has a trailing newline or whitespace
Method 1: Using substr()
Function
The substr()
function is one of the most straightforward ways to remove the last character in PHP.
$str = "Hello!";
$newStr = substr($str, 0, -1);
echo $newStr;
Hello
Explanation: We tell PHP to start at position 0 and go up to the second-last character using -1
. It’s simple and effective for regular strings.
Method 2: Using mb_substr()
for Multibyte Strings
If you're working with Unicode or multibyte strings (like emojis or non-Latin scripts), use mb_substr()
instead to avoid breaking characters.
$str = "Café🌟";
$newStr = mb_substr($str, 0, mb_strlen($str) - 1);
echo $newStr;
Café
This function correctly handles multibyte characters, preserving their integrity.
Method 3: Using rtrim()
to Remove Specific Characters
If you're only looking to remove specific characters (like whitespace or a newline), rtrim()
is ideal.
$str = "Hello world!\n";
$cleaned = rtrim($str);
echo $cleaned;
Hello world!
This will remove whitespace and special characters at the end. However, note that rtrim()
doesn’t remove a specific last character unless it matches a trim pattern.
Method 4: Chaining with strlen()
This is another safe and readable approach using strlen()
with substr()
for clarity:
$input = "PHP7";
$modified = substr($input, 0, strlen($input) - 1);
echo $modified;
PHP
What If the String is Empty?
You should always guard against empty strings to avoid unexpected behavior.
$str = "";
if (strlen($str) > 0) {
echo substr($str, 0, -1);
} else {
echo "Nothing to remove!";
}
Nothing to remove!
Summary
Let’s quickly recap the different ways to remove the last character from a string in PHP:
substr()
– Best for regular ASCII strings.mb_substr()
– Use this for multibyte strings.rtrim()
– Great for trimming known trailing characters.- Always check for empty strings before manipulating them.
Comments
Loading comments...