...

View Full Version : convert \n to <br>



maxhudson
01-14-2011, 04:42 AM
See title :)

How do i do it?

gnomeontherun
01-14-2011, 05:34 AM
Context? Code?

Old Pedant
01-14-2011, 05:44 AM
Where? When?

General answer:


var textWithBrs = textWithNewlines.replace( /\n/g, "<br/>" );


EDIT: Okay, but you probably do *NOT* want to do this with JavaScript.

You probably want to submit the <form> to the server and then let the server-side code do the conversion.

*USUALLY*, thought, it is even better to *NOT* do this conversion until MUCH LATER. You store the text in the DB with the \n newlines. That way, if you want to present it to the user for editing, you simply plop it back into a <textarea> as is, with the \n's still in place.

*ONLY* when you finally retrieve it from the DB and want to display it in a <div> or <span> or such, do you *THEN* do the conversion from \n to <br>... and you *STILL* do it in server side coding. You don't send it to the browser with the \n's in place.

gnomeontherun
01-14-2011, 05:45 AM
Thats not javascript then, use some server side language to validate and replace line breaks with a <br /> tag.

Old Pedant
01-14-2011, 05:52 AM
http://www.lmgtfy.com/?q=replace+a+string+in+php+code

gnomeontherun
01-14-2011, 06:05 AM
Probably need to do that with a preg_replace()

Something like this, but I'm not too good with regex. This is untested.


$clean = preg_replace('/[\n|\r]/m', '<br />', $unclean);

Old Pedant
01-14-2011, 06:30 AM
When you get the field *OUT* of the database, you just use that replace.

Example:



echo preg_replace('/[\n\r]/mg', '<br />', $dbrow["someFieldInTable"] );


I think gnome's answer was not quite correct. You don't use an | or character for choices inside [...]. And he needed a g (global) flag to make sure all occurrences are changed. But I don't use PHP, so I'm not 100% sure on the preg syntax. Just judging by JavaScript and "sed" syntax.

Krupski
01-14-2011, 07:07 AM
basically, when a form is submitted (textarea) i want it to make <br>s instead of \n for line breaks so it works in html..

You should use <p> instead of <br />.

For each newline, replace with a '</p><p>' (that's not a typo).

Then put a <p> at the very beginning of the string and a </p> at the very end.

So, where you had this:

Hi, I'm line one\n
Yeah and I'm line two\n

You get this:

<p>Hi, I'm line one </p><p>Yeah and I'm line two</p>

This way, you have valid DOM elements, rather than one big string of nothing. With valid elements, you can then select and manipulate them if so desired.

If the seemingly large space between paragraphs bothers you, you can always get rid of them with CSS:

{code]
p {
margin:0;
padding:0;
border:0;
}
[/code]

That will make your paragraphs look like <br /> lines.

DJCMBear
01-14-2011, 07:37 AM
Hi, I'm line one\n
Yeah and I'm line two\n

You get this:

<p>Hi, I'm line one </p><p>Yeah and I'm line two</p>


The above example is wrong!

Here is how it would look.

Hi, I'm line one\n
Yeah and I'm line two\n

You get this:

<p>Hi, I'm line one </p><p>Yeah and I'm line two</p><p></p>

The reason being the last \n also being changed to </p><p> as well.

To prevent this use the trim function around the database row.

like so.


echo preg_replace('/[\n\r]/mg', '<br />',trim($dbrow["someFieldInTable"]));


Also why use p tags with styling to make it look like a br tag, as this makes the developer make more work for themselves as it does the same job as when you just enter in a <br /> tag. If you need to use each new line in javascript then yes ok but even with the way you say to set it up this still wont work as there is no identifier on the p tags themselves so you would also then need to code more in javascript to be able to get the new line you want.

Philip M
01-14-2011, 07:52 AM
echo preg_replace('/[\n\r]/mg', '<br />',trim($dbrow["someFieldInTable"]));




Suggest echo preg_replace('/[\n|\r]/mg', '<br />',trim($dbrow["someFieldInTable"]));

DJCMBear
01-14-2011, 08:00 AM
It must be early lol, theres always one mistake in an early code post I got it from post #10 and must have missed that, thanks for pointing it out Philip :)

Philip M
01-14-2011, 08:09 AM
There is no need really to remove the \r\n. They are ignored by HTML.


var val = document.getElementById("textfield").value;
val = val.replace(/\r|\n/g,"<br/>\r\n"); // NB the Javascript \r\n characters are retained
val = val.replace(/(<br\/>\.{0,4}<br\/>\r\n)/g,"<br\/>\r\n"); // remove multiple instances

DJCMBear
01-14-2011, 08:16 AM
Good suggestion but if your doing it through javascript like your example then it wont matter if they are being removed or not as javascript doesn't change the source codes but only the visuals on the page. On the other hand if done in PHP then yes that is a valid point to make :)

Old Pedant
01-14-2011, 08:51 PM
Suggest echo preg_replace('/[\n|\r]/mg', '<br />',trim($dbrow["someFieldInTable"]));


Unless PHP's preg_replace uses completely different syntax than does JavaScript, sed, bash, etc., the | in there would mean you would replace | characters with <br> as well.

Ahh...yes, I am correct:
http://us.php.net/manual/en/regexp.reference.character-classes.php

The | in there is a mistake.

Krupski
01-15-2011, 02:04 AM
The above example is wrong!

Here is how it would look.

Hi, I'm line one\n
Yeah and I'm line two\n

You get this:

<p>Hi, I'm line one </p><p>Yeah and I'm line two</p><p></p>

The reason being the last \n also being changed to </p><p> as well.


Actually, you are also wrong. What initially happens is this:

Hi, I'm line one</p><p>Yeah and I'm line two</p><p>

What I forgot to mention that I also add the opening <p> and the closing </p> afterwards. My mistake. I END UP with what you posted above... after adding the opening and closing tags. ;)


Also why use p tags with styling to make it look like a br tag, as this makes the developer make more work for themselves as it does the same job as when you just enter in a <br /> tag. If you need to use each new line in javascript then yes ok but even with the way you say to set it up this still wont work as there is no identifier on the p tags themselves so you would also then need to code more in javascript to be able to get the new line you want.

Because <p>....text....</p> is a valid DOM entity that can be manipulated whereas ....text<br /> is just a string that has no "identity".

Not that this is bad... ;)

DJCMBear
01-15-2011, 08:12 AM
I read your full post about adding the p tags around the database result and I was saying how the final HTML would look like in the source code not just after the db output edit.

To stop this mistake you could use trim to trim the string before you replace \n\r with <br />


Actually, you are also wrong. What initially happens is this:

Hi, I'm line one</p><p>Yeah and I'm line two</p><p>

What I forgot to mention that I also add the opening <p> and the closing </p> afterwards. My mistake. I END UP with what you posted above... after adding the opening and closing tags. ;)



Because <p>....text....</p> is a valid DOM entity that can be manipulated whereas ....text<br /> is just a string that has no "identity".

Not that this is bad... ;)

venegal
01-15-2011, 03:34 PM
Just for the sake of completeness, and since I haven't seen it mentioned anywhere in this thread, there's PHP's own nl2br (http://php.net/nl2br) function.

When I need a plain text marked up with real paragraphs, I usually use Kohana's auto_p function


/**
* Automatically applies "p" and "br" markup to text.
* Basically [nl2br](http://php.net/nl2br) on steroids.
*
* echo Text::auto_p($text);
*
* [!!] This method is not foolproof since it uses regex to parse HTML.
*
* @param string subject
* @param boolean convert single linebreaks to <br />
* @return string
*/
public static function auto_p($str, $br = TRUE)
{
// Trim whitespace
if (($str = trim($str)) === '')
return '';

// Standardize newlines
$str = str_replace(array("\r\n", "\r"), "\n", $str);

// Trim whitespace on each line
$str = preg_replace('~^[ \t]+~m', '', $str);
$str = preg_replace('~[ \t]+$~m', '', $str);

// The following regexes only need to be executed if the string contains html
if ($html_found = (strpos($str, '<') !== FALSE))
{
// Elements that should not be surrounded by p tags
$no_p = '(?:p|div|h[1-6r]|ul|ol|li|blockquote|d[dlt]|pre|t[dhr]|t(?:able|body|foot|head)|c(?:aption|olgroup)|form|s(?:elect|tyle)|a(?:ddress|rea)|ma(?:p|th))';

// Put at least two linebreaks before and after $no_p elements
$str = preg_replace('~^<'.$no_p.'[^>]*+>~im', "\n$0", $str);
$str = preg_replace('~</'.$no_p.'\s*+>$~im', "$0\n", $str);
}

// Do the <p> magic!
$str = '<p>'.trim($str).'</p>';
$str = preg_replace('~\n{2,}~', "</p>\n\n<p>", $str);

// The following regexes only need to be executed if the string contains html
if ($html_found !== FALSE)
{
// Remove p tags around $no_p elements
$str = preg_replace('~<p>(?=</?'.$no_p.'[^>]*+>)~i', '', $str);
$str = preg_replace('~(</?'.$no_p.'[^>]*+>)</p>~i', '$1', $str);
}

// Convert single linebreaks to <br />
if ($br === TRUE)
{
$str = preg_replace('~(?<!\n)\n(?!\n)~', "<br />\n", $str);
}

return $str;
}

or something like Textile (http://www.textism.com/tools/textile/).

Krupski
01-16-2011, 04:56 AM
I read your full post about adding the p tags around the database result and I was saying how the final HTML would look like in the source code not just after the db output edit.

To stop this mistake you could use trim to trim the string before you replace \n\r with <br />

I'm thinking ahead to reading, quoting and editing previous messages. A posted message may need to be selected, quoted or otherwise manipulated.

If the messages are composed of valid elements (i.e. <p>.....</p> or <div>......</div>, etc...), then they can be identified and anything can be done with them.

Try doing a "getElementByAnything" on a text string terminated with a <br />. :)

Also, data stored in a DB is just bits and bytes. Who cares if the data ends in <br /> or </p>?.

And if you need to drop the data back into a textarea for further editing, it's easy to strip off or convert the offending HTML....



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum