PHP - Trimming Strings with trim(), ltrim(), and rtrim()


PHP provides three useful functions to remove unnecessary white space from strings:

  • trim() removes white space from the beginning and end of a string
  • ltrim() removes white space only from the beginning of a string
  • rtrim() removes white space only from the end of a string

These functions trim white space before or after the text; any white space within the text itself is left intact.

All three functions work in the same way-they take the string to trim as an argument, and return the trimmed string:


$myString = "   this is a test!     ";
echo "|" . trim($myString) . "|\n";  // Displays "|this is a test!|"
echo "|" . ltrim($myString) . "|\n"; // Displays "|this is a test!    |";
echo "|" . rtrim($myString) . "|\n"; // Displays "|   this is a test!|";
?>// w  w  w  . j  a va  2s .  c o  m


You can specify an optional second argument: a string of characters to treat as white space.

The function then trims any of these characters from the string, instead of using the default white space characters.

The white space includes

Character Meaning
"" space
"\t" tab
"\n" newline
"\r" carriage return
"\0" a null byte
"\v" vertical tab

You can use ".." to specify ranges of characters (for example, "1..5" or "a..z").

Here's an example that strips line numbers, colons, and spaces from the start of each line of verse:


$a1 = "1:  this is a test\n";
$a2 = "2:  this is a test.\n";
$a3 = "3:  this is  atest,\n";

echo ltrim($a1, "0..9: ");
echo ltrim($a2, "0..9: ");
echo ltrim($a3, "0..9: ");
?>/*from  w w  w. ja  va2s .c o  m*/


Related Topic