How to Remove the Last Character from a String in PHP

Remove the Last Character from a String in PHP

You may need to cut the last character from a string if it shows by mistake in PHP.

That may be a comma or a period. Also, it can be a slash in a URL. That mistake can ruin the result.

Sometimes the data comes from a loop or a user. Or even an API, and it adds one extra mark that you do not want.

This fix keeps your output clean and avoids problems in layout or file paths.

Here are the common cases:

  • Remove a trailing comma after the loop through a list
  • Fix slashes in folder paths
  • Trim a character before sending text to a database
  • Clean up user input before display

These are small changes that can fix bigger issues in logic.

Use substr() to Remove the Last Character from a String in PHP

You can use substr() to return part of a string. It lets you set where to start and how long to keep.

Here is the syntax:

substr($string, 0, -1);

For example:

$name = "David#";
$clean = substr($name, 0, -1);
echo $clean;

This removes the last character (#) and returns David. It takes all characters from the start to the second-to-last one.

Let’s move on to the following section to see how to achieve the same result with another built-in function in PHP.

Remove the Specific Trailing Characters from a String in PHP with rtrim()

You can also use rtrim() when you want to remove a certain character, not just any last one. It removes a set of characters from the end.

Here is the syntax

rtrim($string, "characters_to_remove");

For example:

$url = "example.com/";
$cleanUrl = rtrim($url, "/");
echo $cleanUrl;

This removes the slash only if it is at the end. It keeps the rest of the string.

You just saw how to clean up targeted characters. In the following part, you will learn how to handle special characters using mb_substr().

Remove the Last Character from a String in PHP with mb_substr() for Multibyte-Safe Character

The mb_substr() works like substr() but supports multibyte characters like emojis and non-English letters. It doesn’t cut a character in half.

It helps you when you work with UTF-8 strings or input from different languages.

Here is an example:

$text = "ありがとう😊";
$short = mb_substr($text, 0, mb_strlen($text) - 1);
echo $short;

This cuts the emoji and keeps the full Japanese word. Without mb_substr(), PHP might break the character.

Let’s take a look at how regular expressions can help in advanced cases.

Remove the Last Character from a String in PHP with preg_replace() and Regex

Regex lets you match patterns and remove the last character only when it matches. It gives you more control.

For example:

$code = "ABC-";
$fixed = preg_replace('/-$/', '', $code);
echo $fixed;

This removes the dash only if it is at the end. If the dash appears elsewhere, it stays untouched.

Examples of How to Remove the Last Character from a String in PHP

Remove trailing period only if it is alone:

$sentence = "Done.";
if (substr($sentence, -1) === ".") {
    $sentence = substr($sentence, 0, -1);
}
echo $sentence;

This checks for a dot at the end and removes it. It does not change if the dot is inside a word.

Clean a tag list like “php,html,css,”:

$tags = "php,html,css,";
$tags = rtrim($tags, ",");
echo $tags;

This trims the last comma but keeps the list readable.

Remove the last character of a path unless it ends with a file:

$path = "/user/data/";
if (is_dir($path)) {
    $path = rtrim($path, "/");
}
echo $path;

It checks if the string is a directory and then removes the slash. It avoids breaking file paths.

Wrapping Up

In this article, you learned how to cut the last character from a string in PHP. You also saw different PHP functions that can do this in more than one way.

Here is a quick recap:

  • Use substr() for simple cuts
  • Use rtrim() for specific character trimming
  • Use mb_substr() for UTF-8 safe trimming
  • Use preg_replace() for pattern-based cleanup

FAQs

How to remove the last character of a string in PHP?

1. Use substr()
$text = "Hello!";
$result = substr($text, 0, -1);
echo $result; // Hello

substr() cuts part of a string. The 0 means start at the first character. The -1 tells PHP to stop before the last character.

2. Use rtrim()
$text = "Hello!";
$result = rtrim($text, "!");
echo $result; // Hello

rtrim() removes chosen characters from the end. Here it removes the !.

3. Use mb_substr() (for UTF-8)
$text = "مرحبا!";
$result = mb_substr($text, 0, -1, "UTF-8");
echo $result; // مرحبا

mb_substr() is safe for Unicode text. It works like substr() but supports multi-byte characters such as Arabic.

Can I remove only slashes or commas from the end?

Yes. Use rtrim($string, "/,") to remove slashes or commas from the end only.

How do I handle strings with emojis or accents?

Use mb_substr() and mb_strlen() to avoid breaking multibyte characters.

What if I want to remove the last character only when it matches a pattern?

Use preg_replace() with a regular expression like /character$/ to match it safely.

Is there a one-size-fits-all function for this?

No. Each method fits a different need. Pick based on the character type, encoding, and condition.

Similar Reads

PHP Comparison Operators Guide with Examples

PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…

PHP fclose(): Close Access of File Manipulation

Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…

Understanding the PHP Exclusive OR (XOR) Operator

In PHP, there is this interesting operator known as "exclusive OR," or just XOR. It is somewhat of an underdog…

PHP array_diff_assoc: How to Compare Arrays with Keys

Array values may look the same, but keys can differ. The array_diff_assoc in PHP finds differences by both values and…

PHP $_COOKIE: Securely Store and Manage Data

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a…

PHP Hello World: Write Your First Program with Code Example

You always start with “Hello World” when you learn a new language. It keeps things simple. You see right away…

filter_has_var Function: Check if Input Exists in PHP

User input does not always come through as expected. Sometimes values are missing or not set at all. This can…

PHP rtrim Function: Remove Trailing Characters or Whitespace

You deal with user input, file reads, or formatted strings. PHP needed a way to remove extra characters from the…

PHP file_exists: Check File and Directory Existence

Whether you are just trying to keep your app from crashing or making sure your users’ uploads don’t accidentally overwrite…

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

Previous Article

Understanding Data Types and Conversion in JavaScript

Next Article

PHP Hello World: Write Your First Program with Code Example

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.