PHP – Collapse multiple line drops to a single line drop

If you need to clean up some input by removing multiple new line drops and replace it with a single new line drop, for example, making this piece of text:

Lorem ipsum dolor sit amet,

consectetur adipiscing elit.
 

Aliquam ac elit at elit viverra mollis.

Cras tincidunt leo eleifend purus fermentum.

Look like this:

Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Aliquam ac elit at elit viverra mollis.
Cras tincidunt leo eleifend purus fermentum.

The following PHP function will remove the consecutive new line characters.

function collapseNewLines($str) {
	return  preg_replace('/((\r?)\n)+/', "\n", $str);
}

Windows/DOS new line is represented by the two characters \r\n and UNIX like systems use only the single char \n . The function handle both cases.
If you find it useful, a link to this blog would be nice 🙂