PHP

How To Remove Whitespaces Using PHP – Examples

If you have read my previous article on how to remove spaces from string, then you would be interested in this article too. In general terms, space is nothing but a gap between two words whereas a “whitespace” could be a tab, a space,  a line feed or a carriage return. The procedure to remove whitespaces from string is a bit different from the procedure to remove spaces from string. In this article, I am going to share a very easy way to use PHP to remove whitespaces from strings by means of examples.

Examples On Using PHP To Remove Whitespace From String

In order to see how to remove white spaces from string using PHP, let’s assume that we have some sample string and it contains spaces, tabs, carriage returns, etc. We will now remove these white spaces from this string.

Example: Using PHP to remove white spaces from string

<?php

$content = "Hello, How are you doing today?		Ok ---    I am going 		...GREAT!!! 

How about yourself?
";

echo 'Original Content:'; echo '<br />';
echo '<pre>'.$content.'</pre>';
echo '<br />';

//Remove all whitespaces from string using the function below
$new_content = preg_replace('/\s+/', '', $content);

echo 'New Content:'; echo '<br />';
echo '<pre>'.$new_content.'</pre>';
echo '<br />';

?>
That’s it!

Do you know of any other ways to remove whitespace from string using PHP? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*