Current Location: Home> Latest Articles> Practical Methods to Remove Trailing Characters from Strings in PHP

Practical Methods to Remove Trailing Characters from Strings in PHP

gitbox 2025-07-17

Removing Trailing Spaces from a String

In PHP, you can use the rtrim() function to remove trailing spaces from a string. This function does not modify the original string but returns a new string with the trailing spaces removed.

$string = "   Hello World   ";
$trimmedString = rtrim($string);
echo $trimmedString; // Output: "   Hello World"

If you need to remove spaces from the left side or both sides of the string, you can use ltrim() or trim() respectively, which work similarly to rtrim().

Removing a Single Trailing Character from a String

To remove a single character from the right end of a string, you can use either the substr() function or substr_replace() function. Here are two examples:

// Using substr() function
$string = "Hello World!";
$trimmedString = substr($string, 0, -1);
echo $trimmedString; // Output: "Hello World"

// Using substr_replace() function
$string = "Hello World!";
$trimmedString = substr_replace($string, '', -1);
echo $trimmedString; // Output: "Hello World"

Removing Multiple Trailing Characters from a String

If you want to remove multiple characters from the right end of a string, you can use the substr() function or combine regular expressions with preg_replace() function.

// Using substr() function
$string = "Hello World!";
$trimmedString = substr($string, 0, -6);
echo $trimmedString; // Output: "Hello"

// Using preg_replace() function
$string = "Hello World!";
$trimmedString = preg_replace('/.{6}$/', '', $string);
echo $trimmedString; // Output: "Hello"

Removing a Specific Trailing Substring from a String

When you need to remove a specific substring from the right end of a string, you can use str_replace() or preg_replace() functions.

// Using str_replace() function
$string = "Hello World!";
$trimmedString = str_replace("World!", "", $string);
echo $trimmedString; // Output: "Hello "

// Using preg_replace() function
$string = "Hello World!";
$trimmedString = preg_replace('/World!$/', '', $string);
echo $trimmedString; // Output: "Hello "

These methods effectively handle different scenarios of removing trailing characters from strings, allowing developers to choose the most suitable approach according to their needs.