Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP rtrim() function

Reference for PHP rtrim() and its alias chop(): remove trailing whitespace, newlines or listed characters from the end of a string, with practical examples.

rtrim() removes characters from the right side (the end) of a string. Without a second argument it strips trailing whitespace, which makes it the usual way to remove the newline at the end of a line read from a file.

chop() is an alias of rtrim(). It has nothing to do with Perl's chop, which removes only the last character, so prefer the name rtrim().

PHP
<?php
echo rtrim("line\n") . "|";     // line|
echo rtrim("1.500", "0");       // 1.5

Try it

PHP Trailing characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Building paths and reading lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
rtrim(string $string, string $characters = " \n\r\t\v\x00"): string
Name Description
$string The input string.
$characters Optional characters to remove, with a..z style ranges.

Return value: the string without trailing characters.

Usage notes

  • Default set: space, \t, \n, \r, \v and the NUL byte.
  • Removes all trailing matches, not one. rtrim("a\n\n") strips both newlines. Use a regex anchored with \z to remove just one.
  • Set semantics: rtrim("file.php", ".php") strips any trailing ., p, h characters and gives "file" by luck, but rtrim("graph.php", ".php") returns "gra". For suffixes use str_ends_with() and substr().
  • Trailing zeros of decimals: rtrim("10.000", "0") leaves "10."; add the dot to the list (".0"), which also damages "100" to "1". Format numbers properly with number_format() instead.
  • Bytes only; use a u regex for Unicode whitespace.
  • Reading files: fgets() keeps the line ending, so rtrim($line, "\r\n") is the common cleanup.