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 echo rtrim("line\n") . "|"; // line| echo rtrim("1.500", "0"); // 1.5
Try it
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.
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
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,\vand the NUL byte. - Removes all trailing matches, not one.
rtrim("a\n\n")strips both newlines. Use a regex anchored with\zto remove just one. - Set semantics:
rtrim("file.php", ".php")strips any trailing.,p,hcharacters and gives"file"by luck, butrtrim("graph.php", ".php")returns"gra". For suffixes usestr_ends_with()andsubstr(). - 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 withnumber_format()instead. - Bytes only; use a
uregex for Unicode whitespace. - Reading files:
fgets()keeps the line ending, sortrim($line, "\r\n")is the common cleanup.
Related
trim(),ltrim(),str_ends_with(),substr()- Lessons: Strings, String functions