display mysql newline in HTML

夙愿已清 提交于 2019-12-29 08:07:58

问题


Certain fields in our mysql db appear to contain newline characters so that if I SELECT on them something like the following will be returned for a single SQL call:

Life to be sure is nothing much to lose

But young men think it is and we were young

If I want to preserve the line breaks when displaying this field on a webpage, is the standard solution to write a script to replace '\n\r' with a br HTML tag or is there a better way?

Thanks!


回答1:


Assuming PHP here...

nl2br() adds in <br /> for every \n. Don't forget to escape the content first, to prevent XSS attacks. See below:

<?php echo nl2br(htmlspecialchars($content)); ?>



回答2:


HTML is a markup language. Regardless of how many linebreaks you put in the source code, you won't see anything from it back in the presentation (of course assuming you aren't using <pre> or white-space:pre). HTML uses the <br> element to represent a linebreak. So you basically indeed need to convert the real and invisible linebreaks denoted by the characters xA (newline, linefeed, LF, \n) and/or xD (carriage return, CR, \r) by a HTML <br> element.

In most programming languages you can just do this by a string replace of "\n" by "<br>".




回答3:


You can wrap it in <pre> .. </pre>.



来源:https://stackoverflow.com/questions/1882754/display-mysql-newline-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!