How to Strip Whitespace from a String with PHP

Whitespace, it can make all the difference in the world when attempting to determine if a string is empty or not. Anytime you are working with user input I recommend stripping whitespace from both sides of the string. When stripping whitespace you can choose to strip from both sides or explicitly the whitespace at the beginning or end of the string.

PHP’s definition of whitespace more than just ordinary spaces, it also includes tabs t, new lines n, carriage returns r, the NUL-byte and the vertical tab x0B.

Strip whitespace from the beginning of a string

echo ltrim('     String!!'

Strip whitespace from the end of a string

echo rtrim('String!!     '

Strip whitespace from both sides of a string

echo trim('     String!!     '
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.