Replacing excessive newlines

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Cut
Forum Commoner
Posts: 39
Joined: Sat Aug 23, 2008 8:01 pm

Replacing excessive newlines

Post by Cut »

I want to replace 3 or more newlines in a row with 2 newlines. I've tried:

Code: Select all

function preparse($val) {
 $val = preg_replace("/(\r\n\r\n\r\n)+|(\n\n\n|\r\r\r)+/", "\n\n", $val);
 return $val;
}
This does not seem to affect input in any way. Halp?
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Replacing excessive newlines

Post by josh »

there can be other hidden characters between newlines (whitespace)
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Replacing excessive newlines

Post by prometheuzz »

Replaces 3 or more empty lines by two:

Code: Select all

$val = preg_replace('/(\r?\n[ \t]*){3,}/', "\n\n\n", $val);
And yes, "\n\n\n" will result in two empty lines.
Post Reply