Today’s guide we are talking about the white spaces in strings and how to remove white spaces in PHP.
The normal way to remove white space is using str_replace.
Remove whitespaces using str_replace
str_replace is very simple and powerful for removing whitespaces.
Use the below script to see this in action.
<?php $str = "he llo how are you "; //apply str_repalce function $str = str_replace(' ', '', $str); print $str; //Output hellohowareyou ?>
When you run this code you will get hellohowareyou as output. Because str_replace function in PHP, replaces every occurrence of space with nothing or empty.
Remove all whitespaces from a string
If you want to remove all kind of whitespaces such as tabbed spaces or invisible end line characters. We can use preg_replace which will do the job for us.
<?php //and a tab character. $string = " Hello\nHow are you\t"; //Remove ALL whitespace characters. $string = preg_replace('/\s+/', '', $string); //var_dump the clean string. var_dump($string);
When you run the above code, you will get the desired output without those tabs and new line character. Which is very good we dealing with large amount of data.
Remove spaces from the beginning and end of a string.
Till now we talked about the whitespaces that are inside the string. But some cases you will have white spaces at the beginning and end of the string. We can use trim in this event.
<?php //at the start and end. $string = " Hello How are you \t\r"; //Trim the string. $string = trim($string); //var_dump the clean string. var_dump($string);
When you run this script, you will notice that the spaces inside the string will be there, but it removes the white spaces from both ends.