Skip to content

Remove Whitespace and line breaks from String using PHP

In PHP we have in-build functions to replace white-space from the start and end of the string these are trim, ltrim and rtrim. These functions are incapable of removing line breaks from the target string, a simple search and replace will not get line breaks.

trim() function will remove white-space from start and end of the given string.
rtrim() function will remove white-space from end of the given string.
ltrim() function will remove white-space from the begging of the string.

You can use preg_replace() function to find all instances of any white-space/line breaks and remove them from the string.

Here is an example code snippet of how you can use the preg_replace() function to remove all the white-space and line breaks from a string.


2 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments