Signup/Sign In

How to Strip All Spaces Out of a String in PHP ?

Answer: Using str_replace() Function

The str_replace() is a built-in function in PHP. This function is used to replace a substring from a string or an array. With the help of this function, we can also remove all the spaces present within the string.

Syntax

str_replace(searchString, replaceString, originalString, count);

Example: Using str_replace() function

Here, we are using str_replace() function to remove spaces from a string in php.

<!DOCTYPE html>
<html>
<head>
	<title>PHP Strip All Spaces Out of a String in PHP</title>
</head>
<body>
	<?php
	$str = 'Welcome to studytonight';
	$new_str = str_replace(' ', '', $str);
	echo $new_str; 
	?>
</body>
</html>

Output


WelcometoStudytonight

By using the str_replace() function, we can remove only white spaces, but what if we want to remove all whitespace, including tabs, newlines, etc. To remove all these at once, PHP offers the preg_replace() function. This function performs a regular expression and replaces all the whitespace, including tabs, newline, etc.

Example: Using preg_replace() function

Here, we are using preg_replace() function to remove spaces from a string in PHP.

<!DOCTYPE html>
<html>
<head>
	<title>PHP Strip All Spaces Out of a String in PHP</title>
</head>
<body>
	<?php
	$str = "Welcome to \n Studytonight \t.";
	$new_str = preg_replace("/\s+/", "", $str);
	echo $new_str; 
	?>
</body>
</html>

Output


WelcometoStudytonight.

Conclusion

In this lesson, we have discussed how to strip all spaces out of a string in PHP. To remove or strip all spaces at once, PHP offers several functions which are the str_replace() function and preg_replace() function. The str_replace() function helps in removing the only whitespace at once, while the preg_replace() function helps in removing all whitespace, including escape sequences such as tabs, newlines, etc.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.