In php, the trim() function is very useful if we have strings with unwanted whitespace. With the php trim() function, we can remove whitespace from the beginning and end of a string.
$variable = " this is a variable ";
echo trim($variable);
//Output:
this is a string 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 beginning and end of a string.
To remove the whitespace at the beginning and end of a string, we 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 End of String with rtrim() in php
If you are looking to remove only the trailing spaces and get rid of all the whitespace at the end of a string, you can use the php rtrim() function.
rtrim(), or “right trim”, removes the 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 at the end of a string.
$variable = " this is a variable ";
echo rtrim($variable);
//Output:
this is a 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 trim() function to remove the leading and trailing spaces of a string variable.