PHP, why sometimes "\ n or \ r" works, but sometimes not?

Well, I'm embarrassed using these things \ r, \ n, \ t etc. Since I'm reading online (php.net), this seems to work, but I try this, here is my simple code:

<?php $str = "My name is jingle \n\r"; $str2 = "I am a boy"; echo $str . $str2; ?> 

But the result: "My name is jingle, I'm a boy"

Either I put \ r \ n in var, or on the same line as echo, the result is the same. Does anyone know why?

+4
source share
6 answers

Since you are outputting the browser, you need to use <br /> instead, otherwise transfer the output to <pre> tags.

Try:

 <?php $str = "My name is jingle <br />"; $str2 = "I am a boy"; echo $str . $str2; ?> 

Or:

 <?php $str = "My name is jingle \n\r"; $str2 = "I am a boy"; echo '<pre>' .$str . $str2 . '</pre>'; ?> 

Browsers will not format non-HTML <pre>serve unless explicitly used with <pre> - they are only interested in HTML.

+14
source

In your example, you have \n\r rather than \r\n - this is rarely a good idea.

Where do you see this result? In a web browser? In page source, still in web browser? What operating system are you using? All of this matters.

Different operating systems use different line terminators, and HTML / XML does not care about line breaks, since a line is split into a source, it simply means “whitespace” (so you get a space between words, but not necessarily a line break).

+4
source

You can also use nl2br ():

 echo nl2br($str . $str2); 

This function replaces the newline characters in your string with <br .

Also, you don't need \ r, just \ n.

+1
source

Use either \ n (* NIX) or \ r \ n (DOS / Windows), \ n \ r is very rare. Once you fix it, it should work fine.

Of course, if you output HTML, a line break does nothing if it is inside <pre> </pre> tags. Use to separate lines in HTML. The nl2br () function can help you convert line breaks to HTML, if necessary.

Also, if you use single-quoted strings (your example has double quotes), \ r and \ n will not work. The only escape characters available in single quotes are \ 'and \.

+1
source

In HTML, spaces, tabs, line feeds, and carriage returns are equivalent spaces.

In the text, historically for newlines , the following combinations were used.

  • \ r on an Apple Mac
  • \ r \ n for Windows
  • \ n on Unix
+1
source

Are you showing the results on an HTML page? if so, the HTML bars scroll as newlines. You need something like using '<br />' instead of '/ r / n' in HTML.

0
source

All Articles