PHP 替换存储在 MySQL DB 中的换行符
我有一个包含 2 列的 MySQL 表:
text
:存储多行文本,其中可能有换行符,如\n、\r、\r\n...< /代码>。文本通过网络表单插入,并且可以由任何操作系统上的任何浏览器插入。
line_break
:表示此特定文本将使用什么类型的换行符(可以是\n
、
、
,...)。这也是由用户通过网络表单插入的。
然后在 PHP 中进行替换:
$text = preg_replace ("/(\r\n|\r|\n)/", $row['line_break'], $row['text']);
有趣的是,如果换行符以 \n
形式存储在数据库中,我实际上会显示 \n
而不是换行符。另一方面,以下正则表达式将正常工作:
$text = preg_replace ("/(\r\n|\r|\n)/", "\n", $row['text']);
How do I need to store the newline in the DB for it to “work”正确?
I have a MySQL table with 2 columns:
text
: stores a multi-line text which could have line breaks as\n, \r, \r\n...
. The text is inserted via a webform and could have been inserted by any browser on any OS.line_break
: represents what type of line break this particular text will use (could be\n
,<br>
,<br />
, ...). This is also inserted via a webform by a user.
In PHP I then do the replacement:
$text = preg_replace ("/(\r\n|\r|\n)/", $row['line_break'], $row['text']);
Interestingly, if the line break is stored in the DB as \n
I will actually show \n
instead of the newline. On the other hand, the following regexp will work correctly:
$text = preg_replace ("/(\r\n|\r|\n)/", "\n", $row['text']);
How do I need to store the newline in the DB for it to "work" correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 php 中,
"\n"
是一种特殊符号,用于书写表示“换行”的特殊字符。但是,如果您将实际文本\n
存储在数据库中,则只有该文本,而不是换行符。当您在 PHP 中编写'\n'
或"\\n"
时,您就会得到什么。确保在数据库中存储实际的换行符,而不是文字\n
文本。In php,
"\n"
is a special notation for writing that special character that means 'line break'. But if you store the actual text\n
in your database, you have just that text, and not the line break character. You have what you get when you write'\n'
or"\\n"
in PHP. Make sure you store the actual line break character in your database and not the literal\n
text.