gpt4 book ai didi

php-5.6 - 为什么 PHP Heredoc 无法保留换行符?

转载 作者:行者123 更新时间:2023-12-02 13:47:00 24 4
gpt4 key购买 nike

docs :

Heredoc text behaves just like a double-quoted string, without the double quotes.

这段代码

<?php
echo "dc:<"."


".">";
echo "hd:<".<<<EOD


EOD
.">";

应该输出:

dc:<


>hd:<


>

但是(在适用于 Windows 的 PHP V5.6.13 上)它输出:

dc:<


>hd:<
>

怎么了?

最佳答案

我对此进行了实验,我认为我可以做出有根据的猜测。

在双引号字符串部分,有 3 个换行符:一个从第 2 行到第 3 行,一个从第 3 行到第 4 行,一个从第 4 行到第 5 行。

在heredoc部分中只有一个换行符。我认为 Heredoc 部分从第一个 EOD 标记之后的行开始,到最后一个 EOD 标记之前的行结束。因此,在您的定界文档中,从第 7 行到第 8 行只有一个换行符,您可以在输出中看到这一点(末尾 <> 之间的换行符)。 如果您向heredoc部分添加更多换行符,那么您将在输出中看到它们。

希望这有助于说明:

<?php
echo "dc:<"." <-- first newline
<-- second newline
<-- third newline
".">";
echo "hd:<".<<<EOD <-- heredoc starts after this part
<-- only one newline here
<-- heredoc ends here so this newline doesn't count
EOD
.">";


回应您的评论:

"In the heredoc section you only have one newline." I have three

是的,但正如我所说,我认为第一个和最后一个换行符被忽略。

"I think that the heredoc section starts on the line AFTER the first EOD token and ends on the line BEFORE the last EOD token" No. See the doc quote I posted.

查看您链接到的文档中的这段文本(强调我的):

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

请注意,它表示字符串本身位于换行符之后。我相信这证明了我的断言,即第一个换行符被省略,因为它是heredoc构造的一部分。诚然,这只能解释第一个换行符。但我相信最后一个换行符出于同样的原因被忽略。

"If you add more newlines to the heredoc section then you will see them in your output." Yup, but still my output has the wrong quantity of newlines.

That quote being: "Heredoc text behaves just like a double-quoted string, without the double quotes."

我认为如果你的双引号字符串部分的结构是这样的......

<?php
echo 'dc:<'.
"
"
.'>';
echo "hd:<".<<<EOD


EOD
.">";

然后它就会像你期望的那样工作。换句话说,这里文档的工作方式与不带双引号的双引号字符串相同。尝试一下。

关于php-5.6 - 为什么 PHP Heredoc 无法保留换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com