954,568 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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

If I have a string like this:

blah
test



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:

// 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.

// Replaces each \n with one br tag each, so huge amounts of linebreaks if huge amount of newlines
$text = preg_replace("/(\n)+/m", '<.br>', $text);

// Same result
$text = preg_replace("/(\n)+/mU", '<.br>', $text);

// Puts a  after every character in my string (definitely not what I wanted)
$text = preg_replace("/(\n)*/m", '<.br>', $text);

// Inserts no newlines
$text = preg_replace("/\n+$/mU", '<.br>', $text);


I'm out of ideas. Anyone know what else I can try?

mmiikkee12
Posting Whiz in Training
274 posts since Oct 2004
Reputation Points: 17
Solved Threads: 5
 

You can definately do that with regex, but I believe without would be faster:

eg:
[PHP]
function my_nl2br($str, $rep = "
", $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...

urolicious
Newbie Poster
13 posts since Oct 2006
Reputation Points: 14
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You