How to replace multiple spaces from a string in PHP

Posted on August 29, 2008, 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!

Get our RSS Feed!

Related Posts

2 Replies to "How to replace multiple spaces from a string in PHP"

  1. 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.”

  2. I agree with the last sentence, but strpos(‘ ‘, $string) !== false is incorrect (because strpos can return also 0 or null), it is better while (strpos(‘ ‘, $string)). I do not understand what do the last command: str_replace(‘ ‘, ‘ ‘, $string).

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)