tags:

views:

116

answers:

3

Hi, I am using nl2br to convert nl chars to
tag but for ex i want to convert "Hello \n\n\n\n Everybody" to "Hello
Everybody" also i want to convert multinewlines to one br tag. How can i do this ?

+8  A: 

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
Thanks for solution. I have one more question. How can i allow 1 and 2 newline ?
mTuran
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
A: 

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
+1  A: 

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