Preserving enters in user's input by PHP
-
19-09-2019 - |
Question
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.
Solution
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 stringDescription
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.
OTHER TIPS
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).