最佳实践:在 PHP 中使用长的多行字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1848945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best Practices: working with long, multiline strings in PHP?
提问by Andrew
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\nthe equivalent of \r\ror \n\r? Which should I use when I'm creating a line gap between lines?
但是换行和回车有什么关系呢?有什么不同?是\n\n相当于\r\r或\n\r?当我在线条之间创建线条间隙时应该使用哪个?
Then there's the option of output buffering and heredoc syntax.
然后是输出缓冲和heredoc 语法的选项。
How do you deal with using long multiline strings in your objects?
您如何处理在对象中使用长多行字符串的问题?
回答by halfdan
You should use HEREDOC or NOWDOC.
您应该使用 HEREDOC 或 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.
Heredoc 和 Nowdoc 之间的区别在于,嵌入在 heredoc 中的 PHP 代码被执行,而 Nowdoc 中的 PHP 代码将按原样打印出来。
$var = "foo";
$text = <<<'EOT'
My $var
EOT;
In this case $text will have the value My $var.
在这种情况下, $text 将具有 value My $var。
Note:before the closing EOT;there should be no spaces or tabs. otherwise you will get an error
注意:在关闭之前EOT;不应有空格或制表符。否则你会得到一个错误
回答by Cvuorinen
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:
我使用与 pix0r 类似的系统,我认为这使代码非常可读。有时我实际上会在双引号中分隔换行符,并对字符串的其余部分使用单引号。这样,如果您使用连接而不是将它们注入双引号字符串中,它们会从文本的其余部分中脱颖而出,并且变量也会更好地脱颖而出。所以我可能会用你原来的例子做这样的事情:
$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.
关于换行符,对于电子邮件,您应该始终使用 \r\n。PHP_EOL 用于在运行 php 的同一操作系统中使用的文件。
回答by powtac
I use templates for long text:
我对长文本使用模板:
email-template.txt contains
email-template.txt 包含
hello {name}!
how are you?
In PHP I do this:
在 PHP 我这样做:
$email = file_get_contents('email-template.txt');
$email = str_replace('{name},', 'Simon', $email);
回答by Pascal MARTIN
Adding \nand/or \rin 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.
添加\n和/或\r在字符串中间,并且有很长的代码行,就像在第二个示例中一样,感觉不对:当您阅读代码时,您看不到结果,您必须滚动.
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, ...
在这种情况下,我总是使用 Heredoc (或 Nowdoc,如果使用 PHP >= 5.3):易于编写,易于阅读,无需超长行,...
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 !
只有一件事:结束标记(以及;它后面的“ ”)必须是其行中唯一的东西:前后没有空格/制表符!
回答by pix0r
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.
当然,您可以使用 HEREDOC,但就代码可读性而言,它并不比第一个示例更好,将字符串包装在多行中。
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.
这可能比 HEREDOC 或多行字符串稍慢,但它会很好地与您的代码缩进一起流动并使其更易于阅读。
回答by johnny
I like this method a little more for Javascript but it seems worth including here because it has not been mentioned yet.
我更喜欢这种用于 Javascript 的方法,但似乎值得包括在这里,因为它尚未被提及。
$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
相关:内爆与连续性能
回答by Alon Gouldman
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();
回答by Dmitriy Sintsov
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
是多行字符串是错误的。那是带有连接运算符的两个字符串,而不是多行字符串。例如,这种连接的字符串不能用作预定义数组的键。不幸的是,php 不提供真正的多行字符串
"abc\n"
"def\n"
only HEREDOCand NOWDOCsyntax, which is more suitable for templates, because nested code indent is broken by such syntax.
onlyHEREDOC和NOWDOC语法,更适合模板,因为嵌套代码缩进被这种语法破坏了。
回答by Corey Ballou
In regards to your question about newlines and carriage returns:
关于您关于换行和回车的问题:
I would recommend using the predefined global constant PHP_EOLas it will solve any cross-platform compatibility issues.
我建议使用预定义的全局常量PHP_EOL,因为它可以解决任何跨平台兼容性问题。
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"
这个问题已经在 SO 上预先提出,您可以通过阅读“我何时使用 PHP 常量 PHP_EOL”来了解更多信息
回答by Sancarn
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?
但是换行和回车有什么关系呢?有什么不同?\n\n 是否等同于 \r\r 或 \n\r?当我在线条之间创建线条间隙时应该使用哪个?
No one here seemed to actualy answer this question, so here I am.
这里似乎没有人真正回答这个问题,所以我来了。
\rrepresents 'carriage-return'
\r代表'回车'
\nrepresents 'line-feed'
\n代表“换行”
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 carriageand then go to a new line. To go to the new line, you would flip a lever which fed the linesto 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.
换行,\n,表示移动到下一行。
A carriage return, \r, means moving the cursor to the beginning of the line.
回车,\r,表示将光标移动到行首。
Ultimately Hello\n\nWorldshould result in the following output on the screen:
最终Hello\n\nWorld应在屏幕上产生以下输出:
Hello
World
Where as Hello\r\rWorldshould result in the following output.
其中 asHello\r\rWorld应该导致以下输出。
It's only when combining the 2 characters \r\nthat you have the common understanding of knew line. I.E. Hello\r\nWorldshould result in:
只有在组合这两个字符时\r\n,您才对已知行有共同的理解。IEHello\r\nWorld应该导致:
Hello
World
And of course \n\rwould result in the same visual output as \r\n.
当然\n\r会产生与\r\n.
Originally computers took \rand \nquite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \non its own. It never depends on the OS, but it does depend on what you're viewing the output in.
最初,计算机采取了\r和\n字面意思。然而,如今对回车的支持很少。通常在每个系统上,您都可以\n自行使用。它从不取决于操作系统,但确实取决于您查看输出的内容。
Still I'd always advise using \r\nwherever you can!
不过我总是建议\r\n尽可能使用!

