Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate break lines with PHP

Tags:

regex

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"

like image 736
dextervip Avatar asked Jan 30 '12 00:01

dextervip


2 Answers

You could use preg_replace:

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

See it working online: ideone

like image 126
Mark Byers Avatar answered Nov 06 '22 00:11

Mark Byers


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

$s = preg_replace("/([\r\n]{4,}|[\n]{2,}|[\r]{2,})/", "\n", $s);
like image 42
M-A-X Avatar answered Nov 05 '22 23:11

M-A-X