Remove Whitespace and line breaks in String
In any programming language there is a simple in-built function you can use to remove whitespace from a string the main one used will be a string replace to search for spaces and replace with empty.
In PHP there are some function which will remove whitespace from the start and end of the string these are trim, ltrim and rtrim. These are good but they will not catch everything you even need to be able to catch line breaks in your space, a simple search and replace will not get line breaks.
Using The Trim Functions
PHP comes with 3 types of trim function there is the standard trim(), the left trim ltrim() and the right trim(). These are all useful in their own right, first the standard trim function is used to remove any whitespace before or after the string.
<?php $string = ' This is an example string '; echo trim($string); // This is display the text This is an example string. ?>
The left trim function ltrim() will only trim the start of the string.
<?php $string = ' This is an example string '; echo ltrim($string); // This is display the text This is an example string . ?>
The right trim function rtrim() will only trim the end of the string.
<?php $string = ' This is an example string '; echo rtrim($string); // This is display the text This is an example string. ?>
PHP Preg_Replace Function
The trim functions can be used to remove the whitespace from simple one line strings but if you have a large textarea and you want to remove the whitespace from this string. The best option to use would be to use the PHP function preg_replace(), find all instances of any whitespace/line breaks and remove them from the string.
Here is an example snippet of how you can use the preg_replace() function to remove all the whitespace and line breaks from a string.
<?php $pattern = '/\s*/m'; $replace = ''; $testString = 'Here is some test text'; $removedWhitespace = preg_replace( $pattern, $replace,$testString ); $removedWhitespace2 = str_replace (' ', '', $testString); echo $removedWhitespace; echo $removedWhitespace2; ?>
Both of these will return the same string but when there is a line break in the test string the first preg_replace will catch these but the second string replace will not.
Gain access to all tutorials
- Premium tutorials covering WordPress, Laravel and VueJS
- Download premium content
- Download premium WordPress plugins
- Only $5 a month
Join the weekly newsletter
Sign up for our newsletter. You'll be updated on new tutorials as they come available.