在PHP中如何折叠heredoc(这里的文档)中的换行符?

时间:2018-01-17 07:02:16

标签: php line-breaks heredoc

出于CLI目的,我想在%%(此处为文档)中部分折叠(忽略换行符)。

目前,我在要删除的行的末尾使用str_replace("%%\n",'', $string);,然后使用<?php $string=<<<EOL This is a single long line, and it has to be in one line, though the SideCI thing (as a coding regulation) I have to line break. But this line stays short. And this line too. And the backslash such as \ won't work. Nor / won't work. My alternative way is to use %% strings and replace them later. EOL; $string .= 'And I don\'t want to do this '; $string .= 'to merge strings.'; echo str_replace("%%\n",'', $string); 替换它们。但我对此感到不舒服。

是否有任何逃生绳或更聪明的方法?

例如:

This is a single long line, and it has to be
in one line, though the SideCI thing (as a 
coding regulation) I have to line break.
But this line stays short.
And this line too.
And the backslash such as \
won't work. Nor /
won't work.
My alternative way is to use strings and replace them later.
And I don't want to do this to merge strings.

我得到如下:

BR

有什么想法吗?

当前结论(2018/01/17)

  

禁用换行符作为默认行为,并使用PHP_EOL标记代替换行符   1.将BR(换行符)替换为&#39;&#39;(空白)   2.将PHP_EOL代码替换为<?php $string=<<<EOL This is a single long line, and it has to be in one line, though the SideCI thing (as a coding regulation) I have to line break.<br> But this line stays short.<br> And this line too.<br> My post alternative way was to use %% chars and replace them later.<br> EOL; $string = str_replace(PHP_EOL,'', $string); $string = str_ireplace(["<br />","<br>","<br/>"], PHP_EOL, $string); echo $string;

示例代码:

<?php
$start_time = time();
$j = 0;
for ($i = 0; $i <= 1000000000; $i++) {
    $j += $i;
}
$end_time = time();
echo "Time Taken: " . ($end_time - $start_time);
echo "\n";
echo "i: " . $i;
echo "\n";
echo "j: " . $j;
echo "\n";
?>

2 个答案:

答案 0 :(得分:1)

我个人会使用像{nbr}这样的内容,因为%%似乎过于通用,{nbr}是&#34;没有中断&#34; {...}在模板中很常见,这只是一个意见。

但我也会使用regx而不是str_replace

preg_replace('/{nbr}[\r\n]+/', '', $str);

这种方式匹配\r\r\n\n甚至\n\n或旧Mac,Windows,Linux和多行结尾。

您可以看到it here:

答案 1 :(得分:1)

您可以使用<br>标记来修改HTML标准,以便说明何时需要换行符。对于习惯HTML的人来说,这会更直观......

$string=<<<EOL
This is a single long line, and it has to be
in one line, though the SideCI thing (as a
coding regulation) I have to line break.
But this line stays short.
And this line too.
And the backslash such as \<br>
won't work. Nor /<br>
won't work.<br>
My alternative way is to use %%<br>
strings and replace them later.

EOL;

$string = str_replace(PHP_EOL,'', $string);
$string = str_ireplace(["<br />","<br>","<br/>"], PHP_EOL, $string);
echo $string;

请注意使用PHP_EOL来使用新线/换行符的正确当前编码或您使用的平台的任何组合。