Replacing many newlines with 1 or 2 <br>'s

Reply

Join Date: Oct 2004
Posts: 274
Reputation: mmiikkee12 is an unknown quantity at this point 
Solved Threads: 5
mmiikkee12's Avatar
mmiikkee12 mmiikkee12 is offline Offline
Posting Whiz in Training

Replacing many newlines with 1 or 2 <br>'s

 
0
  #1
Apr 27th, 2007
If I have a string like this:
  1. blah
  2. test
  3.  
  4.  
  5.  
  6. asdf

What kind of regex would I use to change all single newlines (like between 'blah' and 'test') to <.br> and all multiple newlines (like between 'test' and 'asdf') to a maximum of two <.br>'s?

I've tried these already:
  1. // I had to change br tags to <.br> to make vB not remove them. I don't have a period in the tag in my actual code.
  2.  
  3. // Replaces each \n with one br tag each, so huge amounts of linebreaks if huge amount of newlines
  4. $text = preg_replace("/(\n)+/m", '<.br>', $text);
  5.  
  6. // Same result
  7. $text = preg_replace("/(\n)+/mU", '<.br>', $text);
  8.  
  9. // Puts a <br> after every character in my string (definitely not what I wanted)
  10. $text = preg_replace("/(\n)*/m", '<.br>', $text);
  11.  
  12. // Inserts no newlines
  13. $text = preg_replace("/\n+$/mU", '<.br>', $text);

I'm out of ideas. Anyone know what else I can try?
Last edited by mmiikkee12; Apr 27th, 2007 at 7:51 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 13
Reputation: urolicious is an unknown quantity at this point 
Solved Threads: 2
urolicious's Avatar
urolicious urolicious is offline Offline
Newbie Poster

Re: Replacing many newlines with 1 or 2 <br>'s

 
0
  #2
Apr 28th, 2007
You can definately do that with regex, but I believe without would be faster:

eg:
[PHP]
function my_nl2br($str, $rep = "<br />", $max = 2) {
$arr = explode("\r\n", $str);
$str = '';
$nls = 0;
foreach($arr as $line) {
$str .= $line;
if (empty($line)) {
$nls++;
} else {
$nls = 0;
}
if ($nls < $max) {
$str .= $rep;
}
}
return substr($str, 0, strlen($str) - strlen($rep));
}[/PHP]

Usage:

[PHP]echo my_nl2br2($str);[/PHP]

I haven't tested it though...
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC