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

Learn more

Remove spaces from the beginning and end of a string in php

This php tutorial shows how to remove spaces from the start and end of a string.

Edited: 2014-12-28 03:59

To remove spaces from the beginning and end of a string, we will be using a function called trim – this function allows us to remove obsolete whitespace from the beginning of a string and the end – the php trim function will also remove other whitespace characters, such as: tabs, newlines, and carriage returns.

Sometimes you want to remove certain characters from the end and beginning of stings, this may often be the case with data submitted by users. The extra spaces submitted in content usually doesn't do any harm, as they are typically just collapsed into a single space when viewed in a browser – users sometimes submit extra spaces to force a particular text layout – to remove obsolete whitespace in the entire string, you will have to do something like below, before finally trimming the string.

Remove spaces from the beginning and end of string

After removing obsolete spaces throughout the string, there may still be some leftovers at the beginning and end – the below PHP script will remove whitespace from the start and end of the string, including spaces, newlines, and so on.

The stripped characters can also be specified using the optional second parameter of the trim function, but removing other characters this way may lead to "middle" characters being accidentally removed.

echo trim("ball", 'la'); // Outputs "b" instead of the expected "ba"

The second parameter can also be useful if only you want to remove spaces, while still allowing tabs and newlines. The below PHP script will only remove spaces – the two tabs at the start of the string will be left alone.

See also

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