PHP Trimming

Trimming in PHP is used to clean up the unwanted white spaces of a string. There is no guarantee for the user entered input will always be perfect. Rather, the users can enter their strings with some unwanted space by mistake. Before processing these strings within a PHP script, we need to remove those spaces.

There are three PHP functions for trimming. They perform differently based on the position of the string, where the trimming is going to happen. These functions are listed below.

  • trim() – To strip the white spaces that occur before and after the string to be trimmed.
  • ltrim() – To stripe the white spaces that occur before the string.
  • rtime() – Similarly, this function is used to strip the white spaces at the end of the string.


Each of the above methods has two argument where the first argument is mandatory and the another is optional. The following code shows how to use the PHP trim function and how they are responding.

$strWord = " Welcome\t to\t PHPPOT\n ";
//This line will strip the unwanted white spaces, tabs, 
//and new line breaks from the given string.
$trimmedWord = trim($strWord, " \r\n\t");

The second argument is optional for all trimming functions. If the list of characters to be stripped is not given, then the given string will be clean up from unwanted white spaces only.

This PHP code tutorial was published on May 2, 2013.

↑ Back to Top