How to Strip Whitespace from a String with PHP

Josh Sherman
1 min read
Software Development 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 \0 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!!     ');
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles