Related
Simple, right? Well, this isn't working :-\
$skuList = explode('\n\r', $_POST['skuList']);
Best Practice
As mentioned in the comment to the first answer, the best practice is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).
$skuList = explode(PHP_EOL, $_POST['skuList']);
PHP provides a lot of other very useful constants that you can use to make your code system independent, see this link to find useful and system independent directory constants.
Warning
These constants make your page system independent, but you might run into problems when moving from one system to another when you use the constants with data stored on another system. The new system's constants might be different from the previous system's and the stored data might not work anymore. So completely parse your data before storing it to remove any system dependent parts.
UPDATE
Andreas' comment made me realize that the 'Best Practice' solution I present here does not apply to the described use-case: the server's EOL (PHP) does not have anything to do with the EOL the browser (any OS) is using, but that (the browser) is where the string is coming from.
So please use the solution from #Alin_Purcaru to cover all your bases:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Cover all cases. Don't rely that your input is coming from a Windows environment.
$skuList = preg_split("/\\r\\n|\\r|\\n/", $_POST['skuList']);
or
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Try "\n\r" (double quotes) or just "\n".
If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".
Lots of things here:
You need to use double quotes, not single quotes, otherwise the escaped characters won't be escaped.
The normal sequence is \r\n, not \n\r.
Depending on the source, you may just be getting \n without the \r (or even in unusual cases, possibly just the \r)
Given the last point, you may find preg_split() using all the possible variants will give you a more reliable way of splitting the data than explode(). But alternatively you could use explode() with just \n, and then use trim() to remove any \r characters that are left hanging around.
try
explode(chr(10), $_POST['skuList']);
this php function explode string by newline
Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.pay attention that empty lines will be ignored
function splitNewLine($text) {
$code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
return explode("\n",$code);
}
example
$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );
output
Array
(
[0] => salam
[1] => man khobam
[2] => to chi
[3] => che khabar
[4] => bashe baba raftam
)
It doesn't matter what your system uses as newlines if the content might be generated outside of the system.
I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.
https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n
Code: (Demo)
$text = "one\ntwo\r\nthree\rfour\r\n\nfive";
var_export(preg_split('~\R~', $text));
Output:
array (
0 => 'one',
1 => 'two',
2 => 'three',
3 => 'four',
4 => '',
5 => 'five',
)
Place the \n in double quotes:
explode("\n", $_POST['skuList']);
In single quotes, if I'm not mistaken, this is treated as \ and n separately.
To preserve line breaks (as blank items in the array):
$skuList = preg_split('/\r\n|\n\r|\r|\n/', $_POST['skuList']);`
This handles the unusual \n\r as well as the usual \n\r, \n and \r. Note that the solution from #Alin_Purcaru is very similar, but doesn't handle \n\r.
To remove line breaks (no blank items in the array):
$skuList = preg_split('/[\r\n]+/', $_POST['skuList']);
PHP Tests
These expressions has been tested on the following OS'es: ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15 and in the following PHP versions: 8.0, 7.4, 7.3, 7.2, 7.1, 7.0
Here is the PHP test class:
https://github.com/rosell-dk/exec-with-fallback/blob/main/tests/LineSplittingTest.php
And a successful CI run on a project that runs those tests:
https://github.com/rosell-dk/exec-with-fallback/actions/runs/1520070091
Javascript demos of the principle
Here are some javascript demos of similar regular expressions (I'm using N and R instead of \n and \r).
Preserve linebreaks demo: https://regexr.com/6ahvl
Remove linebreaks demo: https://regexr.com/6ai0j
PS: There is currently a bug in regexr which causes it to show "Error" when first loaded. Editing the expression makes the error go away
For a new line, it's just
$list = explode("\n", $text);
For a new line and carriage return (as in Windows files), it's as you posted. Is your skuList a text area?
Have you tried using double quotes?
Not perfect but I think it must be safest. Add nl2br:
$skuList = explode('<br />', nl2br($_POST['skuList']));
As easy as it seems
$skuList = explode('\\n', $_POST['skuList']);
You just need to pass the exact text "\n" and writing \n directly is being used as an Escape Sequence. So "\\" to pass a simple backward slash and then put "n"
PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Try this:
$myString = "Prepare yourself to be caught
You in the hood gettin' shot
We going throw hell of blows
got my whole frame froze";
$myArray = explode(PHP_EOL, $myString);
print_r($myArray);
First of all, I think it's usually \r\n, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n.
Losing line breaks from posting from input textboxes?
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
this keeps the linebreaks intact in the POST.
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];
Try this:
explode(PHP_EOF, $lines);
Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:
$skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
$skuList = str_replace("\\n\\r", "\n", $skuList);
$skuList = preg_split("/\n/", $skuList);
print_r($skuList);
This method always works for me:
$uniquepattern="##$;?:~#abcz"//Any set of characters which you dont expect to be present in user input $_POST['skuList'] better use atleast 32 charecters.
$skuList=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['skuList'])));
Simple, right? Well, this isn't working :-\
$skuList = explode('\n\r', $_POST['skuList']);
Best Practice
As mentioned in the comment to the first answer, the best practice is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).
$skuList = explode(PHP_EOL, $_POST['skuList']);
PHP provides a lot of other very useful constants that you can use to make your code system independent, see this link to find useful and system independent directory constants.
Warning
These constants make your page system independent, but you might run into problems when moving from one system to another when you use the constants with data stored on another system. The new system's constants might be different from the previous system's and the stored data might not work anymore. So completely parse your data before storing it to remove any system dependent parts.
UPDATE
Andreas' comment made me realize that the 'Best Practice' solution I present here does not apply to the described use-case: the server's EOL (PHP) does not have anything to do with the EOL the browser (any OS) is using, but that (the browser) is where the string is coming from.
So please use the solution from #Alin_Purcaru to cover all your bases:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Cover all cases. Don't rely that your input is coming from a Windows environment.
$skuList = preg_split("/\\r\\n|\\r|\\n/", $_POST['skuList']);
or
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Try "\n\r" (double quotes) or just "\n".
If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".
Lots of things here:
You need to use double quotes, not single quotes, otherwise the escaped characters won't be escaped.
The normal sequence is \r\n, not \n\r.
Depending on the source, you may just be getting \n without the \r (or even in unusual cases, possibly just the \r)
Given the last point, you may find preg_split() using all the possible variants will give you a more reliable way of splitting the data than explode(). But alternatively you could use explode() with just \n, and then use trim() to remove any \r characters that are left hanging around.
try
explode(chr(10), $_POST['skuList']);
this php function explode string by newline
Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.pay attention that empty lines will be ignored
function splitNewLine($text) {
$code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
return explode("\n",$code);
}
example
$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );
output
Array
(
[0] => salam
[1] => man khobam
[2] => to chi
[3] => che khabar
[4] => bashe baba raftam
)
It doesn't matter what your system uses as newlines if the content might be generated outside of the system.
I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.
https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n
Code: (Demo)
$text = "one\ntwo\r\nthree\rfour\r\n\nfive";
var_export(preg_split('~\R~', $text));
Output:
array (
0 => 'one',
1 => 'two',
2 => 'three',
3 => 'four',
4 => '',
5 => 'five',
)
Place the \n in double quotes:
explode("\n", $_POST['skuList']);
In single quotes, if I'm not mistaken, this is treated as \ and n separately.
To preserve line breaks (as blank items in the array):
$skuList = preg_split('/\r\n|\n\r|\r|\n/', $_POST['skuList']);`
This handles the unusual \n\r as well as the usual \n\r, \n and \r. Note that the solution from #Alin_Purcaru is very similar, but doesn't handle \n\r.
To remove line breaks (no blank items in the array):
$skuList = preg_split('/[\r\n]+/', $_POST['skuList']);
PHP Tests
These expressions has been tested on the following OS'es: ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15 and in the following PHP versions: 8.0, 7.4, 7.3, 7.2, 7.1, 7.0
Here is the PHP test class:
https://github.com/rosell-dk/exec-with-fallback/blob/main/tests/LineSplittingTest.php
And a successful CI run on a project that runs those tests:
https://github.com/rosell-dk/exec-with-fallback/actions/runs/1520070091
Javascript demos of the principle
Here are some javascript demos of similar regular expressions (I'm using N and R instead of \n and \r).
Preserve linebreaks demo: https://regexr.com/6ahvl
Remove linebreaks demo: https://regexr.com/6ai0j
PS: There is currently a bug in regexr which causes it to show "Error" when first loaded. Editing the expression makes the error go away
For a new line, it's just
$list = explode("\n", $text);
For a new line and carriage return (as in Windows files), it's as you posted. Is your skuList a text area?
Have you tried using double quotes?
Not perfect but I think it must be safest. Add nl2br:
$skuList = explode('<br />', nl2br($_POST['skuList']));
As easy as it seems
$skuList = explode('\\n', $_POST['skuList']);
You just need to pass the exact text "\n" and writing \n directly is being used as an Escape Sequence. So "\\" to pass a simple backward slash and then put "n"
PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Try this:
$myString = "Prepare yourself to be caught
You in the hood gettin' shot
We going throw hell of blows
got my whole frame froze";
$myArray = explode(PHP_EOL, $myString);
print_r($myArray);
First of all, I think it's usually \r\n, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n.
Losing line breaks from posting from input textboxes?
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
this keeps the linebreaks intact in the POST.
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];
Try this:
explode(PHP_EOF, $lines);
Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:
$skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
$skuList = str_replace("\\n\\r", "\n", $skuList);
$skuList = preg_split("/\n/", $skuList);
print_r($skuList);
This method always works for me:
$uniquepattern="##$;?:~#abcz"//Any set of characters which you dont expect to be present in user input $_POST['skuList'] better use atleast 32 charecters.
$skuList=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['skuList'])));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:
$string='Hi, my name is '.$name
or to embed the variable in the string like this:
$string="Hi, my name is $name";
or is it better to use a function like this:
$string=sprintf("Hi, my name is %s",$name);
Which is better in terms of processor time/efficiency?
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.
Edit: One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! (http://www.weberdev.com/get_example-3750.html points out that it will take 4 times longer to parse those strings)
The difference between single and double quotes in PHP is that double quotes are "intelligent" in that they will parse for variables when being read, while single quotes are "dumb" and will not try to parse any character in the string.
These result in some minor differences in what characters you can use; basically, the only character you need to escape when using single quotes is a single quote itself:
'\''
While if you use double quotes you have to escape other characters:
"\$"
But it also allows for some nifty things like adding a new-line to the end:
"my string\n"
With single quotes you would have to do a concatenation:
'my string' . chr(10)
'my string' . "\n"
Generally, single quotes are faster because they are "dumb".
However, normally one should not really worry about these issues, that is called Premature optimization, and should be avoided.
A couple of words about optimization: generally one should first write the program the way it should work, and then find the biggest bottlenecks and fix those particular ones. If string speed really is an issue for you in PHP, you might want to consider switching to another language.
Regarding speed: you probably want to focus more on memory usage than on CPU time. In these cases the CPU time could be considered pretty constant. CPU time is more relevant when writing algorithms that will iterate many times.
Regarding concatenations: the more you concatenate strings using the dot-operator, the more memory you will be using.
Consider this:
$str1 = 'asdf';
$str2 = 'qwer';
// this will result in more memory being allocated for temporary storage
echo $str1 . $str2;
// this will not allocate as much memory as the previous example
echo $str1;
echo $str2;
I generally feel that using string interpolation ("Hi, my name is $name") is better from a legibility standpoint.
For performance, as others have proven, it is marginally faster to use single quotes rather than double quotes.
Single quotes, if applied to readability science and kept away from subjectivity actually adds more "noise". Noise and how it relates to readability is talked a lot about in the book Clean Code and one could conclude that the more non-whitespace you have to see, the more it hinders readability. If applied to subjectivity, most places that I've taken the time to read actually prefer single over double quotes.
Use your judgement.
$var = "My $string with $lots of $replacements."
Is much more readable than:
$var = 'My ' . $string . ' with ' . $lots . ' of ' . $replacements . '.';
I'll admit that:
$var = "My string.";
Looks almost the same as:
$var = 'My String.';
However the latter introduces less noise and when there's lots of code around it every little bit helps, not to mention the other benefits you get from using single quotes.
In the end, I prefer to KISS. Use single quotes unless you need double quotes. Simple convention that is easier to type, easier to maintain, easier to parse and easier to read.
It doesn't matter from syntax perspective. Both variants are correct. Use what you feel more comfortable.
Personally, I feel better when using the $string="Hi, my name is $name", because you don't need to mess with quotes. Just image the complex SQL query with, let's say, 10 variables...
PHP is pretty slow:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-088-introduction-to-c-memory-management-and-c-object-oriented-programming-january-iap-2010/lecture-notes/MIT6_088IAP10_lec01.pdf
Slide #3
So don't worry too much about little optimizations like these.
Focus more on using APC to cache your code into byte code though. You'll see big speed gains for the project.
Personally, if it's just a normal variable, or even a class property, I'd write it like this:
$newVarA = "This is some text with a $variable";
$newVarB = "This is some more text, written in $settings->language";
However, if I'm using array values then I'll concatenate with single quotes.
$newVarC = 'This is some text from a ' . $text['random'] . ' array';
Hope this makes sense. It's all about finding convention and sticking to it.
My motto and answer is: Leave it to the compilers to write machine code. I will tell you what I mean...
Use single quotes when you don't need to include PHP variables, otherwise use double quotes.
Dont bother about performance just use APC on production servers. Instead focus on writing the most maintainable code; use comments, double quotes etc. properly even though they may slow code down. Every optimization that decreases maintainability / readability of code is bad, leave it to the opcode-cachers and compilers to turn your code into machine code, don't do it yourself... obfuscating your source code because of optimization fires back.
The single quoted string is better option than double quoted string while concatenating the variables.
click the link for better understanding...
http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes
$string='Hi, my name is '.$name
This is the best way, in the sense of php and html combination!
or like this:
$string="Hi, my name is $name";
This is the old way!
Or like this:
$string=sprintf("Hi, my name is %s",$name);
This is what a programmer coming from Visual Basic or other Client Programming languages would write!
I hope I was helpful.
I'm learning PHP and MySQL together from Head First PHP & MySQL and in the book, they often split their long strings (over 80~ characters) and concatenate them, like this:
$variable = "a very long string " .
"that requires a new line " .
"and apparently needs to be concatenated.";
I have no issue with this, but what strikes me odd is that whitespace in other languages usually don't need concatenation.
$variable = "you guys probably already know
that this simply works too.";
I tried this and it worked just fine. Aren't line breaks always interpreted with a space at the end? Even the PHP manual doesn't concatenate in the echo examples if they span over one line.
Should I follow my book's example or what? I can't tell which is more correct or "proper" since both work and the manual even takes a shorter approach. I also would like to know how important is it to keep code under 80 characters in width? I have always been fine with word warp since my monitor is pretty large and I hate my code getting cut short when I have the screen space.
There's 3 basic ways of building multiline strings in PHP.
a. building string via concatenation and embedded newlines:
$str = "this is the first line, with a line break\n";
$str .= "this is the second line, but won't have a break";
$str .= "this would've been the 3rd line, but since there's no line break in the previous line..."`
b. multi-line string assignment, with embedded newlines:
$str = "this is the first line, with a line break\n
this is the second line, because of the line break.
this line will actually is actually part of the second line, because of no newline";
c. HEREDOC syntax:
$str = <<<EOL
this is the first line
this is the second line, note the lack of a newline
this is the third line\n
this is actually the fifth line, because the newline previously isn't necessary.
EOL;
Heredocs are generally preferable for building multi-line strings. You don't have to escape quotes within the text, variables are interpolated within them as if it was a regular double-quoted string, and newlines within the text are honored.
In PHP long strings don't need concatenation but keep in mind that:
$variable = "you guys probably already know
that this simply works too.";
is the equivalent of
$variable = "you guys probably already know\nthat this simply works too.";
The newline is just the same in these 2 examples (if your system uses \n as a newline - Windows uses \r\n).
So to answer your question, no, you don't have to break large strings in many smaller ones. Doing so is just a matter of preference (which I don't really often see).
The 80 char "limit" is throwback to the old days where terminal screens had an 80 char width. If you ever need to edit something in a narrow width terminal, respecting 80 chars can be helpful. However, if longer than 80 char lines wrapping are causing you headaches in your editor, Don't follow that convention.
When you have a multi-line string as in your second example, the string will be exactly as you type it in your editor. If you have a whole bunch of spaces before your retrun char, those will be in your string var. The only exception to this is if your editor is doing line wrapping, then there is not actually a return char in the string, and it won't show up in the variable.
PHP syntax allows literal line feeds in the strings. Your second example equals this:
you guys probably already know[LF][SPACE][SPACE][SPACE][SPACE]that this simply works too.
where [LF] will be \r\n or \n depending on your editor settings. Those redundant spaces may be an issue or not (not everything is HTML), but it's not the same as concatenating.
No.
1) open quotes
2) write as much as you need, adding spaces, tabs, whatever else
3) close quotes.
If you're using the same quotes within, escape them with \
"Jane said \"It's hot today!\"";
or
'Jane said "It\'s hot today!"';
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!