PHP 保存用户输入的内容
如何在数据库中保存用户给出的“输入”并将其显示给其他用户?
我存储用户的问题并使用以下函数来清理用户数据,准备它,并分别执行SQL命令。
pg_escape_string
pg_prepare
pg_execute
我使用 htmlentities
和 ENT_QUOTES
来转换数据 HTML。 此过程删除问题中的所有输入(显然以 \n 形式)。
我想要一个与 SO: 类似的问题系统:仅向用户显示双输入作为换行符。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
htmlentities()
后,调用nl2br()
。 Web 浏览器会忽略普通的换行符,因此您需要将它们转换为
元素才能显示它们。例如:
要仅显示双换行符并忽略单个换行符,您可以使用更复杂的字符串替换函数,
preg_replace
:这里
'/\n\s*\n/'
匹配一个换行符,后跟任意数量的空格,然后是另一个换行符。它用两个
元素替换任何此类子字符串。单个换行符将被忽略。它也很好,因为它会忽略不可见的无关空格和制表符,例如用户输入以下内容:After you call
htmlentities()
, callnl2br()
. The web browser ignores plain newline characters so you need to convert them to<br />
elements to make them show up.For example:
To only show double newlines and ignore single ones, you could instead use a more sophisticated string replacement function,
preg_replace
: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:PHP 的 nl2br() 函数应该可以解决这个问题,并允许您将 \n 字符转换为
html 标记。要启用“换行符两次输入”行为,您应该运行正则表达式将每对连续的
标记转换为单个
标记(您也可以在对文本运行 nl2br() 之前使用 \n 字符执行此操作)。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).