In php, the rtrim() function is very useful if we have strings with unwanted whitespace. With the php rtrim() function, we can remove whitespace from the end of a string.

$variable = "     this is a variable      ";

echo rtrim($variable);

//Output:
     this is a variable

When working with string variables in our php programs, it is useful to be able to easily manipulate and change the value of the variables. One such change is if you want to trim the whitespace from the end of a string.

To remove the whitespace at the end of a string, we can use the php rtrim() function.

rtrim(), or “right trim”, removes the trailing spaces at the end of a string variable.

Below is a simple example of how to use the rtrim() function in php to remove the spaces from the end of a string.

$variable = "     this is a variable      ";

echo rtrim($variable);

//Output:
     this is a variable

Removing Whitespace from Beginning and End of String with php trim() Function

If you are looking to remove both the leading and trailing leading spaces and get rid of all the whitespace at the beginning and end of a string, you can use the php trim() function.

trim() takes in a string and gets rid of the leading and trailing spaces.

Below is a simple example of how to use the trim() function in php to remove the spaces from the beginning and end of a string.

$variable = "     this is a variable      ";

echo trim($variable);

//Output:
this is a string variable

Removing Whitespace from Beginning of String with ltrim() in php

If you are looking to remove only the leading spaces and get rid of all the whitespace at the beginning of a string, you can use the php ltrim() function.

ltrim(), or “left trim”, removes the spaces at the beginning of a string variable.

Below is a simple example of how to use the ltrim() function in php to remove the spaces at the beginning of a string.

$variable = "     this is a variable      ";

echo ltrim($variable);

//Output:
this is a variable      

Hopefully this article has been useful for you to learn how to use the php rtrim() function to remove the trailing spaces of a string variable.

Categorized in:

PHP,

Last Update: February 26, 2024