Backend Development 5 min read

Understanding and Using the PHP rtrim() Function

This article explains the PHP rtrim() function, its syntax, optional character mask, and provides multiple code examples demonstrating how to remove trailing whitespace and specific characters, along with important usage notes and a concise summary.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding and Using the PHP rtrim() Function

The rtrim() function is a built‑in PHP string function that removes whitespace (or other specified characters) from the end of a string.

What is rtrim()?

It trims trailing whitespace characters such as spaces, tabs, and newlines. The basic syntax is:

<code>string rtrim ( string $str [, string $character_mask ] )</code>

$str is the input string, and $character_mask is optional; if omitted, all trailing whitespace is removed.

Usage Examples

1. Remove trailing whitespace

<code>$str = "Hello World    ";
$result = rtrim($str);
echo $result; // Outputs: Hello World</code>

This example defines a string with trailing spaces and uses rtrim() to produce a clean result.

2. Remove a specific character

<code>$str = "Hello World!";
$result = rtrim($str, "!");
echo $result; // Outputs: Hello World</code>

By providing "!" as the character mask, only the exclamation mark at the end is removed.

3. Remove multiple specified characters

<code>$str = "Hello World!";
$result = rtrim($str, "!.");
echo $result; // Outputs: Hello World</code>

Here the mask "!." tells rtrim() to strip both exclamation marks and periods from the string’s end.

Important Notes

The function only affects the end of the string; leading or interior whitespace remains unchanged.

If a $character_mask is supplied, only characters matching the mask are removed from the tail.

rtrim() returns a new string; the original variable is not modified unless you assign the result.

Summary

By mastering the PHP rtrim() function, developers can efficiently clean up trailing whitespace or unwanted characters, improving code readability and maintainability. The article covered syntax, optional masks, practical examples, and key considerations for proper usage.

Recommended PHP Learning Resources

Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial

Vue3+TP6+API Social E‑commerce System Development

Swoole From Beginner to Expert Course

Workerman+TP6 Real‑time Chat System (Limited Offer)

Backendstring-manipulationrtrimphp tutorial
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login 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.