By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 802 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
<title>Title</title>
third line

should give:

first line<br />
<title>Title</title>
third line<br />

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

christian

Jul 17 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
ri******@stud.unibas.ch wrote:
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.


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>
Jul 17 '05 #2

P: n/a

<ri******@stud.unibas.ch> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
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:


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).
Jul 17 '05 #3

P: n/a
Try the nl2br() function:

http://www.php.net/manual/en/function.nl2br.php

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

Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.