Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Multiple Spaces and Newlines with only one space in PHP

I have a string with multiple newlines.

The String:

This is         a dummy text.               I need              




to                                      format
this.

Desired Output:

This is a dummy text. I need to format this.

I'm using this:

$replacer  = array("\r\n", "\n", "\r", "\t", "  ");
$string = str_replace($replacer, "", $string);

But it is not working as desired/required. Some of the words don't have spaces between them.

Actually I need to convert the string with all the words separated by single spaces.

like image 338
Sukanta Paul Avatar asked May 30 '12 04:05

Sukanta Paul


1 Answers

I would encourage you to use preg_replace:

# string(45) "This is a dummy text . I need to format this."
$str = preg_replace( "/\s+/", " ", $str );

Demo: http://codepad.org/no6zs3oo

You may have noted in the " . " portion of the first example. Spaces that are immediately followed by punctuation should probably be removed entirely. A quick modification permits this:

$patterns = array("/\s+/", "/\s([?.!])/");
$replacer = array(" ","$1");

# string(44) "This is a dummy text. I need to format this."
$str = preg_replace( $patterns, $replacer, $str );

Demo: http://codepad.org/ZTX0CAGD

like image 196
Sampson Avatar answered Sep 24 '22 02:09

Sampson