views:

163

answers:

2

How can you preserve "enters" given by the user in the database and show them then to other users?

I store the question of the user and use the following functions to sanitize the user data, prepare it, and execute the SQL command, respectively.

 pg_escape_string
 pg_prepare
 pg_execute

I use htmlentities with ENT_QUOTES to convert the data HTML. This procedure removes all enters, apparently in the form \n, in the question.

I would like to have a similar question-system as in SO: to show only double enters to users as line breaks.

+6  A: 

After you call htmlentities(), call nl2br(). The web browser ignores plain newline characters so you need to convert them to <br /> elements to make them show up.

nl2br — Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string $string [, bool $is_xhtml= true ] )
Returns string with <br /> or <br> inserted before all newlines.

For example:

echo nl2br(htmlentities($input));

To only show double newlines and ignore single ones, you could instead use a more sophisticated string replacement function, preg_replace:

echo preg_replace('/\n\s*\n/', "<br />\n<br />\n", htmlentities($input));

Here '/\n\s*\n/' matches a newline, followed by any amount of whitespace, followed by another newline. It replaces any such substring with two <br /> elements. Single newlines are ignored. It's also nice because it'll ignore extraneous spaces and tabs that are invisible, such as if a user typed this:

This is a paragraph.\n
It is pretty short.\n
<space><tab>\n
Here's another paragraph.\n
It too is short.

John Kugelman
@John - it shouldn't matter if he calls it before or after htmlentities. Still though, +1 for the preg_replace example.
karim79
No no, careful. The order matters: if you call `htmlentities` after `nl2br` it'll mess up all those `<br />` tags.
John Kugelman
@John - I stand corrected, guess I shouldn't be SOing at 4:30 am.
karim79
Careful with this: Some browsers post newlines as <br>. htmlentities() would mess everything. A "br2nl" before the htmlentities() would be appropriate.
Havenard
+1  A: 

PHP's nl2br() function should do the trick and allow you to convert \n characters to <br> html tags.

To enable the "two enters for a newline" behavior, you should run a regex to turn every pair of consecutive <br> tags into a single <br> tag (you could also do this with \n characters before running nl2br() on the text).

Lior Cohen
Could be nice if the downvoters could leave a comment as to why they chose to downvote the answer. If there's anything wrong with the answer I've provided above, I'd like to know. People come here for the learning experience - myself included :P
Lior Cohen