PHP `rtrim()` function

Example

Remove characters from the right side of the string:

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

Run Instances

Definition and Usage

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

Related Functions:

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

syntax

rtrim(string,charlist)
Parameter Description
string Required. Specify the string to be checked.
charlist

Optional. Specify which characters to remove from the string. If omitted, the following characters are removed:

  • "\0" - NULL
  • "\t" - Tab
  • "\n" - Newline
  • "\x0B" - Vertical Tab
  • "\r" - Carriage Return
  • " " - Space

Technical Details

Return Value: Return the modified string.
PHP Version: 4+
Update Log: Added in PHP 4.1 charlist Parameter.

More Examples

Example 1

Remove spaces from the right of the string:

<?php
$str = "Hello World!    ";
echo "Do not use rtrim: " . $str;
echo "<br>";
echo "Use rtrim: " . rtrim($str);
?>

The HTML output of the above code is as follows (view source code):

<!DOCTYPE html>
<html>
<body>
Do not use rtrim: Hello World!    <br>Use rtrim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use rtrim: Hello World!
Use rtrim: Hello World!

Run Instances

Example 2

Remove newline characters (\n) from the right of the string:

<?php
$str = "Hello World!\n\n\n";
echo "Do not use rtrim: " . $str;
echo "<br>";
echo "Use rtrim: " . rtrim($str);
?>

The HTML output of the above code is as follows (view source code):

<!DOCTYPE html>
<html>
<body>
Do not use rtrim: Hello World!
<br>Use rtrim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use rtrim: Hello World!
Use rtrim: Hello World!

Run Instances