php

How to remove all spaces from a string in PHP

In this tutorial, we are going to see how to remove all spaces from a string in PHP. You can simply use the PHP str_replace() function to remove all spaces from a string. Let’s look at the following example to see how it actually works:
 

How to remove all spaces from a string in PHP
<?php
	$str = 'Welcom to StackHowTo.';
	$replaced = str_replace(' ', '', $str);
	echo $replaced;
?>

Output:

WelcomtoStackHowTo.
 
In the example above we remove only spaces. If you want to remove all spaces, including tabs, newlines, etc., you can use the preg_replace() function, which searches and replaces according to a regular expression, as shown in the following example:

<?php
	$str = 'Welcom to StackHowTo.';
	$replaced = preg_replace("/\s+/", "", $str);
	echo $replaced;
?>

Output:

WelcomtoStackHowTo.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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