How to replace all new lines of string with `<BR>` in php?

妖精的绣舞 提交于 2021-02-19 09:13:29

问题


There are too much confusion about \n and \r.
There are lot's of questions in stack about differences between \n and \r. In a nut shell My confusions/questions are:

  1. Is \r\n equal to \n\r?
  2. Is \r\n cause to two new lines?
  3. Is \r cause a new line in output?
  4. How can I replace all new lines with <BR> tag in PHP?

Not all strings has \r or \n explicitly. Suppose I have a textarea and user inputs some characters including Enter of keyboard. No \r or \n is entered but new lines exist. How to remove all new lines?


回答1:


Microsoft Windows / MS-DOS: \r\n

Acorn BBC and RISC OS spooled text output: \n\r

Apple Macintosh OS 9 and earlier: \r

Unix (e.g., Linux), also Apple OS X and higher: \n

replace -> nl2br

more on that here

If new lines exists in the textarea than \n,\r or \r\n are present! These are control characters which are not outputted.

To remove them you could try:

$string = str_replace(array("\r\n", "\n\r", "\r", "\n"), "", $string);


来源:https://stackoverflow.com/questions/16376090/how-to-replace-all-new-lines-of-string-with-br-in-php

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