PHP rtrim

Created with Sketch.

PHP rtrim

Summary: in this tutorial, you’ll learn how to use the PHP rtrim() function to remove whitespace or other characters from the end of a string.

Introduction to the PHP rtrim() function

To remove the whitespace characters or other characters from the end of a string, you use the PHP rtrim() function.

The following shows the syntax of the rtrim() function:

rtrim ( string $string , string $characters = " \n\r\t\v\0" ) : string

Code language: PHP (php)

The rtrim() has two parameters:

  • $string is the input string.
  • $characters is one or more characters that you want to strip from the end of the string.

By default, the rtrim() function removes the characters from the list ” \n\r\t\v\0″ from the end of the string:

CharacterASCIIHexDescription
” “320x20a space
“\t”90x09a tab
“\n”100x0Aa new line
“\r”130x0Da return
“\0”00x00a NUL-byte
“\v”110x0Ba vertical tab

If you want to strip other characters, you can specify them in the $characters argument.

The rtrim() function doesn’t change the input string ($string). Instead, it returns a new string with the $characters stripped off.

PHP rtrim() function examples

Let’s take some examples of using the rtrim() function.

1) Using the PHP rtrim() function to remove whitespace characters

The following example uses the rtrim() function to strip all the space characters from the end of a string:

<?php

$name = 'John Doe ';
$clean_name = rtrim($name);

var_dump($clean_name);

Code language: PHP (php)

Output:

string(8) "John Doe"

Code language: PHP (php)

2) Using the PHP rtrim() function to remove other characters

Suppose that you have the following string:

<?php

$paragraph = "Hello! How are you? I'm here.";

Code language: PHP (php)

And you want to turn it into an array of strings that don’t have the period (.), question mark(?), and exclamation mark (!).

To do that, you can use the preg_split() funtion to split the string into sentences:

<?php

$paragraph = "Hello! How are you? I'm here.";
$sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $paragraph);

print_r($sentences);

Code language: PHP (php)

Output:

Array
(
[0] => Hello!
[1] => How are you?
[2] => I'm here.
)

Code language: plaintext (plaintext)

And then you use the rtrim() function to remove the period (.), question mark(?), and exclamation mark (!):

<?php

$paragraph = "Hello! How are you? I'm here.";

// split into sentences
$sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $paragraph);

// remove endings
$endings = '.?!';
$results = array_map(fn ($s) => rtrim($s, $endings), $sentences);

print_r($results);

Code language: PHP (php)

Output:

Array
(
[0] => Hello
[1] => How are you
[2] => I'm here
)

Code language: plaintext (plaintext)

Summary

  • Use the PHP rtrim() function to remove the whitespace or other characters from the end of a string.

Leave a Reply

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