Categories
PHP / MySQL

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.

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

Leave a Reply

Your email address will not be published. Required fields are marked *