THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP rtrim() Function

PHP String Reference PHP String Reference

Example

Remove characters from the right side of a string:

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

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 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 1

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!
Run example »

Example 2

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!
Run example »

PHP String Reference PHP String Reference