Skip to content
PHP rtrim() Function: Description, Parameters, Return Value, and Usage Examples

PHP rtrim() Function: Description, Parameters, Return Value, and Usage Examples

This article explains PHP's rtrim() function, detailing its syntax, parameters, default characters removed, and provides multiple code examples demonstrating how to trim whitespace, custom character masks, and ASCII control characters from the end of strings.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community

The article introduces PHP's rtrim() function, which removes whitespace or specified characters from the end of a string.

Syntax: string rtrim(string $str [, string $character_mask]) Parameters: • $str: The input string. • $character_mask (optional): A list of characters to strip; ranges can be specified with ...

Return value: The function returns the trimmed string. Without a mask, it removes the following characters: space (0x20), tab (0x09), newline (0x0A), carriage return (0x0D), NUL (0x00), and vertical tab (0x0B).

Example usage:

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

Output of the example:

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"

An additional example shows how to strip all ASCII control characters from a binary string using a mask like "\x00..\x1F", demonstrating the flexibility of rtrim() for custom trimming needs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPString Manipulationrtrimcharacter masktrim functions
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.