Strip all spaces from a string in PHP
This article demonstrates how to strip all spaces from a string in PHP.
1. Using str_replace() function
The str_replace() function is used to replace all occurrences of the search string with the replacement string. To remove all spaces from the string, you can use space (" ") as the search string and an empty string ("") as the replacement string.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $str = " Hello, World "; $str = str_replace(" ", "", $str); echo $str; /* Output: Hello,World */ ?> |
The above solution only removes the space character from the string. However, it doesn’t remove any other type of whitespace character, which is composed of spaces, tabs, or line breaks. In order to remove all whitespace from the string, you would have to invoke the str_replace() function multiple times, once for each whitespace character.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $str = " Hello, World "; $str = str_replace(" ", "", $str); // remove spaces $str = str_replace("\t", "", $str); // remove tabs $str = str_replace("\r\n", "", $str); // remove line break echo $str; /* Output: Hello,World */ ?> |
2. Using preg_replace() function
To strip all whitespace characters from the string, you can use the regular expression \s+ which matches one or more whitespace characters. In PHP, you can use the preg_replace() function to perform search and replace using a regex.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $str = " Hello, World "; $str = preg_replace("/\s+/", "", $str); echo $str; /* Output: Hello,World */ ?> |
You can extend the above solution to remove only excess whitespace from a string. The following solution replaces consecutive whitespace characters with a single space, and also removes all leading and trailing whitespace from the string with trim() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $str = " Hello, World "; $str = trim(preg_replace("/\s\s+/", " ", $str)); echo $str; /* Output: Hello, World */ ?> |
That’s all about stripping all spaces from a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)