Page 1 of 1
Regex problem
Posted: Fri May 23, 2003 7:59 am
by ILoveJackDaniels
I've got a problem with what I think should be a relatively simple regex. I'm processing form entries, and they may have large numbers of new lines. I want to replace any instance of two or more new lines with two HTML line breaks, but not replace single new lines. So what I've tried is this:
Code: Select all
eregi_replace("(\n){2,}", "<br> <br>", $input)
Instead of replacing all of the new lines, it replaces them in pairs, even where there are 4 or 5 in a row. Any ideas?
Posted: Fri May 23, 2003 9:52 am
by patrikG
Try:
Code: Select all
<?php
eregi_replace("(\r\n){2,}", "<br> <br>", $input)
?>
Posted: Fri May 23, 2003 9:56 am
by volka
if you don't mind that it uses pcre

Code: Select all
$output = preg_replace('!(?:\r?\n){2,}!m', "<br> <br>", $input);
(untested)
edit: oops, too late
my pattern differs from patrikG's in
- pcre instead of ereg
- using only grouping not fetching , (?: ) instead of ()
- \r is optional (not all systems use crlf)
Posted: Fri May 23, 2003 10:01 am
by ILoveJackDaniels
Woohoo, thanks patrik and volka

. It's perfect

Posted: Fri May 23, 2003 10:03 am
by liljester
if its windows you may want to strip out the carriage returns as well.
Code: Select all
<?php
str_replace(chr(13), "", $input);
eregi_replace("(\n)+\n", "<BR><BR>", $input);
?>