Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to trim whitespace from a string

Short answer

trim() strips spaces, tabs and line breaks from both ends:

<?php
 
var_dump(trim('  text  '));

Output:

string(4) "text"

One side only

ltrim() strips the start of the string, rtrim() the end:

<?php
 
var_dump(ltrim('  text  '));
var_dump(rtrim('  text  '));

Output:

string(6) "text  "
string(6) "  text"

Extra spaces inside the string

trim() leaves the middle of the string alone. A regular expression collapses repeated spaces into one:

<?php
 
echo preg_replace('/\s+/', ' ', 'one   two    three');

Output:

one two three

Functions used in this recipe

  • trim — Removes whitespace and other characters from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.