Regex problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
ILoveJackDaniels
Forum Commoner
Posts: 43
Joined: Mon May 20, 2002 8:18 am
Location: Brighton, UK

Regex problem

Post 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)&#123;2,&#125;", "<br>&nbsp;<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?
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

Try:

Code: Select all

<?php
eregi_replace("(\r\n){2,}", "<br> <br>", $input)
?>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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)
User avatar
ILoveJackDaniels
Forum Commoner
Posts: 43
Joined: Mon May 20, 2002 8:18 am
Location: Brighton, UK

Post by ILoveJackDaniels »

Woohoo, thanks patrik and volka :). It's perfect :)
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post 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);
?>
Post Reply