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 threeFunctions used in this recipe
- trim — Removes whitespace and other characters from both ends of a string.