How to remove multiple spaces and newlines from a string in PHP?

I have a form with a text area, I need to remove a few spaces and some new lines from the line I entered here.
I wrote this function to remove some spaces

function fix_multi_spaces($string)
{
    $reg_exp = '/\s+/';
    return preg_replace($reg_exp," ",$string);
}

This function works well for spaces, but also replaces newlines, changing them to one space.
I need to change a few spaces to 1 place and some new lines to 1 new line.
How can i do

+3
source share
3 answers

Using

preg_replace('/(( )+|(\\n)+)/', '$2$3', $string);

; (, \t ) , .

, ( , ) ( ).

:. , , ( craniumonempty !). , , ,

preg_replace('/(?|( )+|(\\n)+)/', '$1', $string);
+5

, \s regex , , , ..

, preg_replace - ...

-1

You can use the following function to replace multiple spaces and rows with one space ...

function test($content_area){

//Newline and tab space to single space

$content_area = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $content_area);

// Multiple spaces to single space ( using regular expression)

$content_area = ereg_replace(" {2,}", ' ',$content_area);

return $content_area;

}
-1
source

All Articles