PHP rtrim() Function

❮ PHP String Reference

Example

Remove characters from the right side of a string:

<?php
$str = "Hello World!";
echo $str . "<br>";
echo rtrim($str,"World!");
?>
Try it Yourself »

Definition and Usage

The rtrim() function removes whitespace or other predefined characters from the right side of a string.

Related functions:

  • ltrim() - Removes whitespace or other predefined characters from the left side of a string
  • trim() - Removes whitespace or other predefined characters from both sides of a string

Syntax

rtrim(string,charlist)

Parameter Values

Parameter Description
string Required. Specifies the string to check
charlist Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
  • "\0" - NULL
  • "\t" - tab
  • "\n" - new line
  • "\x0B" - vertical tab
  • "\r" - carriage return
  • " " - ordinary white space


Technical Details

Return Value: Returns the modified string
PHP Version: 4+
Changelog: The charlist parameter was added in PHP 4.1

More Examples

Example

Remove whitespaces from the right side of a string:

<?php
$str = "Hello World!    ";
echo "Without rtrim: " . $str;
echo "<br>";
echo "With rtrim: " . rtrim($str);
?>

The HTML output of the code above will be (View Source):

<!DOCTYPE html>
<html>
<body>

Without rtrim: Hello World!    <br>With rtrim: Hello World!
</body>
</html>

The browser output of the code above will be:

Without rtrim: Hello World!
With rtrim: Hello World!
Try it Yourself »

Example

Remove newlines (\n) from the right side of a string:

<?php
$str = "Hello World!\n\n\n";
echo "Without rtrim: " . $str;
echo "<br>";
echo "With rtrim: " . rtrim($str);
?>

The HTML output of the code above will be (View Source):

<!DOCTYPE html>
<html>
<body>

Without rtrim: Hello World!


<br>With rtrim: Hello World!
</body>
</html>

The browser output of the code above will be:

Without rtrim: Hello World!
With rtrim: Hello World!
Try it Yourself »

❮ PHP String Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.