HPM HPM - 23 days ago 13
PHP Question

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

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?

Answer

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);