Remove whitespace from strings

Опубликовано: 29 Апрель 2026
на канале: PHP Explained
118
1

We can use function trim() to remove white space and other predefined characters from both sides of a string.

Here are the top features of this function.
1. It contains two parameters. First parameter is mandatory. It is actual string that we are trimming.

2. Second parameter is optional. It contains the characters to remove from the string. If nothing is mentioned then a few characters will be removed. These characters are white space, null, tab, vertical tab, carriage return, and new line.
" " - ordinary white space
"\0" - NULL
"\t" - tab
"\v" - vertical tab
"\r" - carriage return
"\n" - new line

3. It returns a string after trimming the original string.
4. It is a built-in function of PHP.
5. It is introduced since PHP 4.
6. There are two related built-in functions, ltrim() and rtrim(). These are doing exactly the same things as function trim(), but with respect to left side and right side of the string respectively.

Let's see an example. We are trimming white space from both sides of the string.
$str = " Hi there ";
echo trim($str);

Let's try another example. Original string contains 14 characters. We specify to remove white space and new line from both sides of the string. The new string after trimming contains 10 characters.
$str = " Hi \n\nthere \n ";
echo "without trim - " . strlen($str) . "\n";
echo "with trim - " . strlen(trim($str, " \n")) . "\n";