PHP, why sometimes "\n or \r" works but sometimes doesnt? - 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?

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.

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

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.

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

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

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.

Related

why remove "\n","\r","\t" in phalcon?

I found that in the muilti-module which is created by phalcon-tool has these code:
$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());
Why remove "\n","\r","\t"?
As Spangen pointed out, these are the escape sequences for some special 'whitespace' characters.
This link here has more information on them: http://us3.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Now, an important note: for them to work as intended in PHP, you need to enclose them in double quotes, like: "\t", "\n". Single quotes won't produce the intended effects of these escape sequences: '\t', '\n'.
To illustrate this more, you can run this code and see the results. Running it from console like php myfile.php might cause some visual glitches, and running it in the browser will need that you view the 'source code'.
echo "Let's test... ";
echo "Because no new line characters were added, this sentence will be printed in the same line as the previous phrase.";
echo "\n";
echo "But now a new line was added, by typing \\n enclosed in double quotes.";
echo "\n";
echo "Now, let's add a tab, between the next two words: hello \t there.";
echo "\n";
echo "Now, let's add a carriage return, which will 'force' the 'cursor' in this string to move to the beginning, thus 'splitting' this string into two. Adding it now: \r There, I just added it before this last sentence.";
echo "\n";
echo 'Finally, these special characters will not work as intended if we just enclose the string with single quotes, as done in this string: \n \t \r';
This link here has more information on the difference between new lines and carriage returns: https://stackoverflow.com/a/12747850/466395
So yeah, in the original code that you posted, the person removed those special characters using str_replace(), because they tend to produce 'visual glitches' (unintented malformed output) in console.
This is to replace newlines, line feeds and tabs with a single space so that the application's details can be written to STD_OUT as a single line with no wrapping.

How to use nl2br to remove \n and add breaks

I'm having some trouble getting nl2br to do what I want.
Can someone explain why nl2br doesn't change the \n in the JSON data to < br /> in my PHP?
Here is the code:
$page = file_get_contents('JSON_FEED_URL');
$page2 = nl2br($page);
When I echo $page2 and view the HTML page it comes out as a big wall of text.
Try
$page = file_get_contents('JSON_FEED_URL');
$page2 = preg_replace("/\\n/m", "<br />", $page);
As said, str_replace would also work a tad faster, but the above counts of multiline breaks.
nl2br does not replace the new lines, only ads the <br> tags. In HTML there is no need to remove the new line characters as they are considered to be white space which is collapsed to a single space for display. This fact is the very reason for having the <br> tag.
Since you say that you can see the \ns when echoing (instead of a newline in the source), this probably means that your \ns are literal, and not "proper" newlines. This is because your JSON is read as a string. Fix this by calling json_decode();
$page2 = nl2br(json_decode($page));
Explanation:
The string
line1
line2
is in JSON saved as
"line1\nline2"
but that \n is not a real newline, just normal characters. By decoding the JSON, it will be correct.
nl2br did not interpret \n to <br /> in HTML because they were literal slashes followed by n.
On your source, the text looks like the following:
FRIDAY THROUGH WEDNESDAY.\n\nMORE RAIN IS
Should be something similar to the ff so that it'll be interpreted:
FRIDAY THROUGH WEDNESDAY.
MORE RAIN IS
You can address your problem by using str_replace() or if you can update your code when putting content on "JSON_FEED_URL", add nl2br before putting those content.

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

PHP Linefeeds (\n) Not Working

For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.
Example:
error_log('test\n', 3, 'error.log');
error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document
I'm pretty sure you are outputting to a html file.
The problem is html ignores newlines in source which means you have to replace the newlines with <br/> if you want a newline in the resulting page display.
You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');
to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);
It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.
Double quotes are what you want. Single quotes ignore the \ escape. Double quotes will also evaluate variable expressions for you.
Check this page in the php manual for more.
The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>
If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.

Best Practices: working with long, multiline strings in PHP?

Note: I'm sorry if this is an extremely simple question but I'm somewhat obsessive compulsive over the formatting of my code.
I have a class that has a function that returns a string that will make up the body text of an email. I want this text formatted so it looks right in the email, but also so it doesn't make my code look funky. Here's what I mean:
class Something
{
public function getEmailText($vars)
{
$text = 'Hello ' . $vars->name . ",
The second line starts two lines below.
I also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
return $text;
}
}
but it could also be written as:
public function getEmailText($vars)
{
$text = "Hello {$vars->name},\n\rThe second line starts two lines below.\n\rI also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
return $text;
}
but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?
Then there's the option of output buffering and heredoc syntax.
How do you deal with using long multiline strings in your objects?
You should use heredoc or nowdoc.
$var = "some text";
$text = <<<EOT
Place your text between the EOT. It's
the delimiter that ends the text
of your multiline string.
$var
EOT;
The difference between heredoc and nowdoc is that PHP code embedded in a heredoc gets executed, while PHP code in nowdoc will be printed out as is.
$var = "foo";
$text = <<<'EOT'
My $var
EOT;
In this case $text will have the value "My $var", not "My foo".
Notes:
Before the closing EOT; there should be no spaces or tabs. otherwise you will get an error.
The string/tag (EOT) that enclose the text is arbitrary, that is, one can use other strings, e.g. <<<FOO and FOO;
EOT : End of transmission, EOD: End of data. [Q]
I use similar system as pix0r and I think that makes the code quite readable. Sometimes I would actually go as far as separating the line breaks in double quotes and use single quotes for the rest of the string. That way they stand out from the rest of the text and variables also stand out better if you use concatenation rather than inject them inside double quoted string. So I might do something like this with your original example:
$text = 'Hello ' . $vars->name . ','
. "\r\n\r\n"
. 'The second line starts two lines below.'
. "\r\n\r\n"
. 'I also don\'t want any spaces before the new line,'
. ' so it\'s butted up against the left side of the screen.';
return $text;
Regarding the line breaks, with email you should always use \r\n. PHP_EOL is for files that are meant to be used in the same operating system that php is running on.
I use templates for long text:
email-template.txt contains
hello {name}!
how are you?
In PHP I do this:
$email = file_get_contents('email-template.txt');
$email = str_replace('{name},', 'Simon', $email);
Adding \n and/or \r in the middle of the string, and having a very long line of code, like in second example, doesn't feel right : when you read the code, you don't see the result, and you have to scroll.
In this kind of situations, I always use Heredoc (Or Nowdoc, if using PHP >= 5.3) : easy to write, easy to read, no need for super-long lines, ...
For instance :
$var = 'World';
$str = <<<MARKER
this is a very
long string that
doesn't require
horizontal scrolling,
and interpolates variables :
Hello, $var!
MARKER;
Just one thing : the end marker (and the ';' after it) must be the only thing on its line : no space/tab before or after !
Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.
If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:
$text = "Hello, {$vars->name},\r\n\r\n"
. "The second line starts two lines below.\r\n"
. ".. Third line... etc";
This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.
I like this method a little more for Javascript but it seems worth including here because it has not been mentioned yet.
$var = "pizza";
$text = implode(" ", [
"I love me some",
"really large",
$var,
"pies.",
]);
// "I love me some really large pizza pies."
For smaller things, I find it is often easier to work with array structures compared to concatenated strings.
Related: implode vs concat performance
you can also use:
<?php
ob_start();
echo "some text";
echo "\n";
// you can also use:
?>
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then:
$long_text = ob_get_clean();
In regards to your question about newlines and carriage returns:
I would recommend using the predefined global constant PHP_EOL as it will solve any cross-platform compatibility issues.
This question has been raised on SO beforehand and you can find out more information by reading "When do I use the PHP constant PHP_EOL"
The one who believes that
"abc\n" . "def\n"
is multiline string is wrong. That's two strings with concatenation operator, not a multiline string. Such concatenated strings cannot be used as keys of pre-defined arrays, for example. Unfortunately php does not offer real multiline strings in form of
"abc\n"
"def\n"
only HEREDOC and NOWDOC syntax, which is more suitable for templates, because nested code indent is broken by such syntax.
but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?
No one here seemed to actualy answer this question, so here I am.
\r represents 'carriage-return'
\n represents 'line-feed'
The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:
A line feed,\n, means moving to the next line.
A carriage return, \r, means moving the cursor to the beginning of the line.
Ultimately Hello\n\nWorld should result in the following output on the screen:
Hello
World
Where as Hello\r\rWorld should result in the following output.
It's only when combining the 2 characters \r\n that you have the common understanding of knew line. I.E. Hello\r\nWorld should result in:
Hello
World
And of course \n\r would result in the same visual output as \r\n.
Originally computers took \r and \n quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n on its own. It never depends on the OS, but it does depend on what you're viewing the output in.
Still I'd always advise using \r\n wherever you can!

Categories