3

I am using nl2br() to convert \n characters to the <br /> tag but I do not want more than one <br /> tag at a time. For example, Hello \n\n\n\n Everybody should become Hello <br /> Everybody.

How can I do this?

Lemmings19
  • 1,383
  • 3
  • 21
  • 34
mTuran
  • 1,846
  • 4
  • 32
  • 58

3 Answers3

8

The most direct approach might be to first replace the multiple newlines with one using a simple regular expression:

nl2br(preg_replace("/\n+/", "\n", $input));
VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
  • Thanks for solution. I have one more question. How can i allow 1 and 2 newline ? – mTuran Sep 07 '09 at 23:42
  • If you want to preserve up to two `\n` characters, just put two of them in the regular expression and replacement: `preg_replace("/\n\n+/", "\n\n", $input)` – VoteyDisciple Sep 08 '09 at 01:41
3

If you have php 5.2.4+ you can use preg_replace and the vertical whitespace character type \v

$str = preg_replace('/\v+/','<br>', $str);
rojoca
  • 11,040
  • 4
  • 45
  • 46
1

I'd try replacing repeated newlines with single newlines using preg_replace() first, then using nl2br to convert to HTML
tags. nl2br(preg_replace('/\n+/', '\n', $the_string)) should do the trick (untested).

Twisol
  • 2,762
  • 1
  • 17
  • 17