943,522 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 5514
  • PHP RSS
Apr 27th, 2007
0

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

Expand Post »
If I have a string like this:
PHP Syntax (Toggle Plain Text)
  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:
php Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 17
Solved Threads: 5
Posting Whiz in Training
mmiikkee12 is offline Offline
274 posts
since Oct 2004
Apr 28th, 2007
0

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

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...
Reputation Points: 14
Solved Threads: 2
Newbie Poster
urolicious is offline Offline
13 posts
since Oct 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: php tutorial
Next Thread in PHP Forum Timeline: need help in php





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC