tags:

views:

244

answers:

6

Well, I am abit confuse using these \r,\n,\t etc things. Because I read online (php.net), it seems like works, but i try it, here is my simple code:

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

    echo $str . $str2;
?>

But the outcome is "My name is jingle I am a boy"

Either I put the \r\n in the var or in the same line as echo, the outcome is the same. Anyone knows why?

+12  A: 

Because you are outputting to a browser, you need to use a <br /> instead, otherwise wrap your output in <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 <pre>serve non-HTML formatting unless made explicit using <pre> - they are interested only in HTML.

karim79
This is a good answer, but having \n\r is bad as Jon points out.
RichardOD
+3  A: 

Well in your example you've got \n\r rather than \r\n - that's rarely a good idea.

Where are you seeing this outcome? In a web browser? In the source of a page, still in a web browser? What operating system are you using? All of these make a difference.

Different operating systems use different line terminators, and HTML/XML doesn't care much about line breaking, in that the line breaks in the source just mean "whitespace" (so you'll get a space between words, but not necessarily a line break).

Jon Skeet
LF is Unix-like and CR+LF is Windows. LF+CR is as Jingleboy99 has is just wrong.
RichardOD
what is LF and CR??
jingleboy99
LF = Line Feed (\n); CR = Carriage Return ('\r')
Jon Skeet
A: 

Are you displaying the results in an HTML page? if so, HTML strips whitespace like newlines. You'd have to something like use '<br />' instead of '/r/n' in HTML.

mishac
+1  A: 

You could also use nl2br():

echo nl2br($str . $str2);

What this function does is replace newline characters in your string to <br>.

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

Lior Cohen
+1  A: 

Either use \n (*NIX) or \r\n (DOS / Windows), \n\r is very uncommon. Once you fix that, it should work just fine.

Of course, if you're outputting HTML, a line break does nothing unless it's inside <pre></pre> tags. Use <br /> to separate lines in HTML. The nl2br() function can help you to convert line breaks to HTML if needed.

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

Thorarin
+1  A: 

In HTML, spaces, tabs, linefeeds and carriage returns are all equivalent white space characters.

In text, historically the following combinations have been used for newlines

  • \r on Apple Macs
  • \r\n on Windows
  • \n on Unix
Paul Dixon