PHP rtrim | Remove Characters from End of String

PHP rtrim is an inbuilt function in PHP. It removes whitespaces (or other characters) from the end of a string. In this article, we will discuss the PHP rtrim Function. Also, we will discuss a few examples of using it.

Related Articles:

Syntax

rtrim($string, $characterList)

Parameters

The PHP rtrim Function expects two parameters. However, only one parameter is mandatory and the other is optional.

  • $string: The first parameter to the function is the string to operate on. It is a mandatory parameter.
  • $characterList: The second parameter to the function is an optional parameter. It specifies the character list to remove from the string. By default, the function removes all the following characters:
    • “\0” – NULL
    • “\t” – tab
    • “\n” – new line
    • “\x0B” – vertical tab
    • “\r” – carriage return
    • ” ” – ordinary white space

Return Value

The rtrim function in PHP returns the string after removing whitespaces and all other predefined characters from the right side (end of the string).

Note: The function returns an empty string when the argument is a null variable.

PHP rtrim function

Examples

Let’s discuss a few examples of using the PHP rtrim function.

Example 1: Removing Whitespaces

For instance, consider a simple string containing whitespaces on both ends.

<?php

	$string = '   Simple   string ';
	$trimmedString = rtrim($string);

	var_dump($trimmedString);

?>

In the above example, the function removes whitespaces only from the right end. The spaces from on the left side remain as it is.

OUTPUT:
string(15) "   Simple   string"

Example 2: Specifying Characters to Remove

Also, we can specify characters to remove by passing the second parameter.

<?php
$str = "Hello World!";
echo $str;
//Remove "d!" in "World!"
echo rtrim($str,"Hed!");
?>

The above example will print the following. You can notice that the function removes the “d!” from the end of the string. However, the “He” from the beginning of the string remains as it is.

OUTPUT:
Hello World!
Hello Worl

Example 3: Removing Whitespaces from Array of Strings

Similarly, you can remove whitespaces from an array of strings using PHP array_map. We can pass the rtrim function as callback in array_map function.

<?php

$fruit = array('apple','banana ', ' mango ');

$trimmedArray = array_map('rtrim', $fruit);
var_dump($trimmedArray);

?>

The above example will print the following:

OUTPUT:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana"
  [2]=>
  string(6) " mango"
}

Conclusion

In conclusion, we discussed the PHP rtrim Function. You can read more about it on PHP Official Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *