][\n\r]+/" with "

Replacing "/[^>][\n\r]+/" with "

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hi all,

I would like to replace line breaks such '[\n\r]+' with '<br />'. Easy
task. Problems start when I try to only replace lines that do not end
with HTML tags.
I tried preg_replace("/[^>][\n\r]+/", "<br />\n") but this does not
seem to work.
An example to better understand what I would like to achieve:

first line
third line

should give:

first line<br />
third line<br />

Any help would be grateful appreciated. Thanks and have a nice day,


Re: Replacing "/[^>][\n\r]+/" with "

Try the nl2br() function:


"Given a string, convert any line breaks to <br>"

Re: Replacing "/[^>][\n\r]+/" with "

Quoted text here. Click to load it

That wouldn't work correctly when you have a "\r\n" after a tag, since "\n"
would match as it doesn't immediately follow >.

Converting "\r\n" to "\n" first will make life easier:

$text = str_replace("\r\n", "\n", $text);
$text = preg_match('/(?<!>)\n/', "<br />\n", $text);

(?<! ... ) is a lookbehind negative assertion. It means that the preceding
text should not match the pattern (an < in this case).

Re: Replacing "/[^>][\n\r]+/" with "

ribchr00@stud.unibas.ch wrote:

Quoted text here. Click to load it

I've been guilty of gymnastics with regexes in the past, but these days I
prefer the simple, readable route:

//$line = "<test>\n";
$line = "test\n";
if( !preg_match( '/>[\n\r]+$/', $line ) ) {
  $line = preg_replace("/[\n\r]+$/", "<br />\n", $line );
echo $line;

Not tested, but it looks about right. :o)

The email address used to post is a spam pit. Contact me at
http://www.derekfountain.org : <a
href="http://www.derekfountain.org /">Derek Fountain</a>

Site Timeline