By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Remove spaces from the beginning of a string with PHP

How to remove spaces or other characters from the start of a string. Just another PHP tutorial.

Edited: 2012-12-22 18:48

Here will show how to remove spaces from the beginning of a string. The function that we will be using is called ltrim, it is used in the same way as the rtrim function – the only difference is that the ltrim function will effect the left side of a string, while rtrim will effect the right side.

It is also possible to remove other characters than spaces, to do that you will need to use the second parameter – called charlist – of the function, to list the characters that you want removed. The below script shows how to trim the right side of a string:

 $text = "\t\tThis example string contains two tabs at the start, and a single tab and some spaces at the end\t    ";
 $rtrimmed = rtrim($text);
 echo $rtrimmed; // only the tabs at the start of the string has been removed!

Removing other characters

The ltrim function also allows you to specify exactly what characters that should be removed. As we mentioned earlier in the PHP tutorial, this is done using the second parameter of the function. The example below will show you how to use this second parameter:

 $text = "abc abcdefg";
 $rtrimmed = rtrim($text, "abc");
 echo $rtrimmed;

Note. The string will be re-checked, meaning that both "abc" parts will be removed from the start.

More PHP Tutorials

  1. Remove spaces from the beginning and end of a string
  2. Remove spaces from end of string