PHP rtrim() Function

Usage — The PHP rtrim() function is used to strip whitespace or other predefined characters from the end of a string.

It has the following syntax:

PHP

string rtrim ( string $str [, string $character_mask ] )

Here is an example of using rtrim():

PHP

$str = "Hello World!  \n";

// Output — string(12) "Hello World!"
var_dump(rtrim($str));

Return Value — This function returns the modified string with the whitespace (or other characters) stripped from the end of str.

Additional Information — Without the second parameter, rtrim() will strip these characters: " " an ordinary space, "\t" a tab, "\n" a new line, "\r" a carriage return, "\0" the NULL-byte and "\x0B" a vertical tab.

PHP Version and Changelog — The rtrim() function is available in PHP 4, PHP 5, PHP 7. The character_mask parameter was added in PHP 4.1.

Relevant Functions — Other related PHP functions that you should know about are: trim() which strips whitespace (or other characters) from the beginning and end of a string and ltrim() which strips whitespace (or other characters) from the beginning of a string.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

str

The str parameter is used to specify the input string. This is a required parameter.

character_mask

The character_mask parameter is used to specify the characters that you want to strip. You simply have to list all characters that you want to be stripped. You can also use .. to specify a range of characters that you want to trim. This is an optional parameter.

When this parameter is omitted, all of the following characters are removed: NULL, tab, new line, vertical tab, carriage return and ordinary white space.

Working Examples

Here are some examples of using the rtrim() function:

PHP

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);
/* Output —
    string(32) "        These are a few words :) ...  "
    string(16) "    Example string
    "
    string(11) "Hello World" */

$trimmed = rtrim($text);
var_dump($trimmed);
/* Output —
    string(30) "        These are a few words :) ..." */

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);
/* Output —
    string(26) "        These are a few words :)" */

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);
/* Output —
    string(9) "Hello Wor" */

$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);
/* Output —
    string(15) "    Example string" */

Here is another example that makes the working of the rtrim() function more clear:

PHP

$text = "This string contains some unwanted characters at the end.";

$text1 = rtrim($text, 'a..z');
// Output — "This string contains some unwanted characters at the end."
echo $text1;

$text1 = rtrim($text1, '.');
// Output — "This string contains some unwanted characters at the end"
echo $text1;

$text2 = rtrim($text, 'a..z.');
// Output — "This string contains some unwanted characters at the  "
echo $text2;

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. I have an obsessive love for php’s array functions given how extremely easy they’ve made complex string handling for me in various situations… so, have another string-rtrim() variant:

    PHP

    function strrtrim($message, $strip) {
        // break message apart by strip string
        $lines = explode($strip, $message);
        $last  = '';
        // pop off empty strings at the end
        do {
            $last = array_pop($lines);
        } while (empty($last) && (count($lines)));
        // re-assemble what remains
        return implode($strip, array_merge($lines, array($last)));
    }
    

    Suggested by - pinkgothic at gmail dot com

  2. On the recurring subject of string-stripping instead of character-stripping rtrim() implementations… the simplest (with a caveat) is probably the basename function. It has a second parameter that functions as a right-trim using whole strings:

    PHP

    echo basename('MooFoo', 'Foo');
    
    ...outputs 'Moo'.

    Since it also strips anything that looks like a directory, it’s not quite identical with hacking a string off the end:

    PHP

    echo basename('Zoo/MooFoo', 'Foo');
    
    ...still outputs 'Moo'.

    But sometimes it gets the job done.

    Suggested by - pinkgothic at gmail dot com

  3. This shows how rtrim() works when using the optional charlist parameter: rtrim() reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the “new” last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly “rtrimmed” string is returned.

    PHP

    // Example 1:
    rtrim('This is a short short sentence', 'short sentence');
    // Returns 'This is a'
    // If you were expecting the result to be 'This is a short ',
    // then you're wrong; the exact string, 'short sentence',
    // isn't matched.  Remember, character-by-character comparison!
    
    // Example 2:
    rtrim('This is a short short sentence', 'cents');
    // returns 'This is a short short '
    

    Suggested by - todd at magnifisites dot com

Further Reading

  1. You can read more about the PHP rtrim() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top