Php – Remove excessive line returns

phpwhitespace

I am looking for something like trim() but for within the bounds of a string. Users sometimes put 2, 3, 4, or more line returns after they type, I need to sanitize this input.

Sample input

i like cats


my cat is happy
i love my cat



hope you have a nice day

Desired output

i like cats

my cat is happy
i love my cat

hope you have a nice day

I am not seeing anything built in, and a string replace would take many iterations of it to do the work. Before I whip up a small recursive string replace, I wanted to see what other suggestions you all had.

I have an odd feeling there is a regex for this one as well.

Best Solution

function str_squeeze($body) {
    return preg_replace("/\n\n+/", "\n\n", $body);
}
Related Question