dextervip
dextervip

Reputation: 5069

How to remove duplicate break lines with PHP

I would like to know how could I remove duplicate break lines with PHP considering that the input can be from various OS.

Input Ex.: "02 02 02 02 \r\n\r\n 02 02 02 02 \r\n 02 02 02 02"

Input Ex.: "02 02 02 02 \n\n\n 02 02 02 02 \n\n 02 02 02 02"

Output Ex.: "02 02 02 02 \n 02 02 02 02 \n 02 02 02 02"

Upvotes: 9

Views: 11228

Answers (2)

M-A-X
M-A-X

Reputation: 492

More quickly is to replace only 2+ line breaks :) :

$s = preg_replace("/([\r\n]{4,}|[\n]{2,}|[\r]{2,})/", "\n", $s);

Upvotes: 9

Mark Byers
Mark Byers

Reputation: 838696

You could use preg_replace:

$s = preg_replace("/[\r\n]+/", "\n", $s);

See it working online: ideone

Upvotes: 25

Related Questions