How to replace multiple spaces from a string in PHP
Posted on August 29, 2008, Filled under PHP,
Bookmark it
This snippet is useful when you need to replace multiple spaces from a string. Tabs, New Lines and Carriages are also replaced.
<?php
function replace_multiple_spaces($string)
{
// tabs, new lines and carriages are also replaced
$string = ereg_replace("[ \t\n\r]+", " ", $string);
return $string;
}
$string = "This
is
a dummy
text. ";
$new_string = replace_multiple_spaces($string);
// Outputs: This is a dummy text
echo $new_string;
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- August 29, 2008
- article by Gabriel C.
- 1 comment
Related Posts
Format text into a SEO Friendly Stringat August 28, 2008 with 1 comment
Update table field by replacing a string value with a new oneat August 28, 2008
Create, Customize and Send Newsletters: MeeNewsat August 3, 2009 with 1 comment

One Reply to "How to replace multiple spaces from a string in PHP"
May 20, 2010 at 5:23 PM
ereg_replace is almost deprecated from PHP, better to use preg_replace instead. And even when you will change to preg_replace this code will be 5 times slower than
while (strpos(‘ ‘, $string) !== false) $string = str_replace(‘ ‘, ‘ ‘, $string);
So the main idea is: “When you can write your code in a couple of lines without regular expressions – do it.”