GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Downloads
  • Documentation
  • Get Involved
  • Help
  • Getting Started
  • Introduction
  • A simple tutorial
  • Language Reference
  • Basic syntax
  • Types
  • Variables
  • Constants
  • Expressions
  • Operators

This view

  • Original page
  • New address

GeezerVison is showing www.php.net — PHP: rtrim - Manual

PHP 8.6.0 RC5 available for testing
    setlocale »
    « quotemeta
    • Preface
    • Function Reference
    • Text Processing
    • Strings
    • String Functions

    rtrim

    (PHP 4, PHP 5, PHP 7, PHP 8)

    rtrim — Strip whitespace (or other characters) from the end of a string

    Description

    function rtrim(string $string, string $characters = " \f\n\r\t\v\x00"): string

    This function returns a string with whitespace (or other characters) stripped from the end of string.

    Without the second parameter, rtrim() will strip these characters:

    • " ": ASCII SP character 0x20, an ordinary space.

    • "\t": ASCII HT character 0x09, a tab.

    • "\n": ASCII LF character 0x0A, a new line (line feed).

    • "\r": ASCII CR character 0x0D, a carriage return.

    • "\0": ASCII NUL character 0x00, the NUL-byte.

    • "\v": ASCII VT character 0x0B, a vertical tab.

    • "\f": ASCII FF character 0x0C, a form feed (as of PHP 8.6.0).

    Parameters

    string

    The input string.

    characters

    Optionally, the stripped characters can also be specified using the characters parameter. Simply list all characters that need to be stripped. With .. it is possible to specify an incrementing range of characters.

    Return Values

    Returns the modified string.

    Changelog

    Version Description
    8.6.0 The form feed character ("\f") was added to the default value of characters.

    Examples

    Example #1 Usage example of rtrim()

    <?php
    
    $text = "\t\tThese are a few words :) ...  ";
    $binary = "\x09Example string\x0A";
    $hello  = "Hello World";
    var_dump($text, $binary, $hello);
    
    print "\n";
    
    $trimmed = rtrim($text);
    var_dump($trimmed);
    
    $trimmed = rtrim($text, " \t.");
    var_dump($trimmed);
    
    $trimmed = rtrim($hello, "Hdle");
    var_dump($trimmed);
    
    // trim the ASCII control characters at the end of $binary
    // (from 0 to 31 inclusive)
    $clean = rtrim($binary, "\x00..\x1F");
    var_dump($clean);
    
    ?>

    The above example will output:

    string(32) "		These are a few words :) ...  "
    string(16) "	Example string
    "
    string(11) "Hello World"
    
    string(30) "		These are a few words :) ..."
    string(26) "		These are a few words :)"
    string(9) "Hello Wor"
    string(15) "	Example string"

    See Also

    • trim() - Strip whitespace (or other characters) from the beginning and end of a string
    • ltrim() - Strip whitespace (or other characters) from the beginning of a string

    Found A Problem?

    Learn How To Improve This Page • Submit a Pull Request • Report a Bug
    +add a note

    User Contributed Notes 6 notes

    up
    down
    47
    pinkgothic at gmail dot com ¶
    16 years ago
    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)));
    }
    
    ?>
    
    Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
    up
    down
    29
    gbelanger at exosecurity dot com ¶
    20 years ago
    True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()
    
    ---
    
    Here's a quick way to recursively trim every element of an array, useful after the file() function :
    
    <?php
    # Reads /etc/passwd file an trims newlines on each entry
    $aFileContent = file("/etc/passwd");
    foreach ($aFileContent as $sKey => $sValue) {
        $aFileContent[$sKey] = rtrim($sValue);
    }
    
    print_r($aFileContent);
    ?>
    up
    down
    26
    todd at magnifisites dot com ¶
    23 years ago
    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 '
    ?>
    up
    down
    15
    pinkgothic at gmail dot com ¶
    13 years ago
    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.
    up
    down
    16
    Unimagined at UnaimaginedDesigns dot Com ¶
    21 years ago
    I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.  
    
    <?php
    
    class cleaner {
    
    function cleaner ($cuts,$pinfo) {
    $ucut = "0";
    $lcut = "0";
    while ($cuts[$ucut]) {
    $lcut++;
    $ucut++;
    }
    $lcut = $lcut - 1;
    $ucut = "0";
    $rcut = "0";
    $wiy = "start";
    
    while ($wiy) {
    
    if ($so) {
    $ucut = "0";
    $rcut = "0";
    unset($so);
    }
    
    if (!$cuts[$ucut]) {
    $so = "restart";
    } else {
    $pinfo = rtrim($pinfo);
    $bpinfol = strlen($pinfo);
    $tcut = $cuts[$ucut];
    $pinfo = rtrim($pinfo,"$tcut");
    $pinfol = strlen($pinfo);
    
        if ($bpinfol == $pinfol) {
        $rcut++;
        if ($rcut == $lcut) {
        unset($wiy);
        }
        $ucut++;
        } else {
        $so = "restart";
        }
    }
    }
    
    $this->cleaner = $pinfo;
    }
    
    }
    
    $pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";
    
    $cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');
    
    $pinfo = new cleaner($cuts,$pinfo);
    $pinfo = $pinfo->cleaner;
    
    print $pinfo;
    
    ?>
    
    That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
    up
    down
    4
    harmor ¶
    18 years ago
    I'm sure there's a better way to strip strings from the end of strings.
    
    <?php
    /**
     * Strip a string from the end of a string
     *
     * @param string $str      the input string
     * @param string $remove   OPTIONAL string to remove
     *  
     * @return string the modified string
      */
    function rstrtrim($str, $remove=null)
    {
        $str    = (string)$str;
        $remove = (string)$remove;    
        
        if(empty($remove))
        {
            return rtrim($str);
        }
        
        $len = strlen($remove);
        $offset = strlen($str)-$len;
        while($offset > 0 && $offset == strpos($str, $remove, $offset))
        {
            $str = substr($str, 0, $offset);
            $offset = strlen($str)-$len;
        }
        
        return rtrim($str);    
        
    } //End of function rstrtrim($str, $remove=null)
    
    echo rstrtrim('Hello World!!!', '!')   .'<br />'; //"Hello World"
    echo rstrtrim('Hello World!!!', '!!')  .'<br />'; //"Hello World!"
    echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
    echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
    ?>
    +add a note
    • String Functions
      • addcslashes
      • addslashes
      • bin2hex
      • chop
      • chr
      • chunk_​split
      • convert_​uudecode
      • convert_​uuencode
      • count_​chars
      • crc32
      • crypt
      • echo
      • explode
      • fprintf
      • get_​html_​translation_​table
      • hebrev
      • hex2bin
      • html_​entity_​decode
      • htmlentities
      • htmlspecialchars
      • htmlspecialchars_​decode
      • implode
      • join
      • lcfirst
      • levenshtein
      • localeconv
      • ltrim
      • md5
      • md5_​file
      • metaphone
      • nl_​langinfo
      • nl2br
      • number_​format
      • ord
      • parse_​str
      • print
      • printf
      • quoted_​printable_​decode
      • quoted_​printable_​encode
      • quotemeta
      • rtrim
      • setlocale
      • sha1
      • sha1_​file
      • similar_​text
      • soundex
      • sprintf
      • sscanf
      • str_​contains
      • str_​decrement
      • str_​ends_​with
      • str_​getcsv
      • str_​increment
      • str_​ireplace
      • str_​pad
      • str_​repeat
      • str_​replace
      • str_​rot13
      • str_​shuffle
      • str_​split
      • str_​starts_​with
      • str_​word_​count
      • strcasecmp
      • strchr
      • strcmp
      • strcoll
      • strcspn
      • strip_​tags
      • stripcslashes
      • stripos
      • stripslashes
      • stristr
      • strlen
      • strnatcasecmp
      • strnatcmp
      • strncasecmp
      • strncmp
      • strpbrk
      • strpos
      • strrchr
      • strrev
      • strripos
      • strrpos
      • strspn
      • strstr
      • strtok
      • strtolower
      • strtoupper
      • strtr
      • substr
      • substr_​compare
      • substr_​count
      • substr_​replace
      • trim
      • ucfirst
      • ucwords
      • vfprintf
      • vprintf
      • vsprintf
      • wordwrap
    • Deprecated
      • convert_​cyr_​string
      • hebrevc
      • money_​format
      • utf8_​decode
      • utf8_​encode
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.