Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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?

like image 210
jingleboy99 Avatar asked Nov 29 '22 20:11

jingleboy99


2 Answers

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.

like image 177
karim79 Avatar answered Dec 06 '22 15:12

karim79


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

like image 38
Jon Skeet Avatar answered Dec 06 '22 17:12

Jon Skeet