出于 CLI 的目的,我想在heredoc
(此处文档)中
部分折叠(忽略换行符)。
目前,我在要折叠的行的末尾使用
%%
,然后使用 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
1.将(换行符)替换为''(空白)。PHP_EOL
2.将标签替换为BR
.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;
您可以使用
<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
来使用新行/换行符的正确当前编码或您使用的平台的任何组合。
就我个人而言,我会使用像
{nbr}
这样的东西,因为 %%
看起来太笼统了,其中 {nbr}
是“不间断”,而 {...}
在模板中很常见,这只是一个意见。
但我也会使用 regx 而不是 str_replace
preg_replace('/{nbr}[\r\n]+/', '', $str);
这样它匹配
\r
、\r\n
、\n
甚至\n\n
或旧Mac、Windows、Linux和多行结尾。
你可以在这里看到它:
这就是我添加的方式 在 heredoc
<?php
$return_str ='';
$newline_char = "\n";
for($i=0; $i <5 ;$i++)
{
$return_str .= <<<abcd
A random new line $newline_char
abcd;
}
echo $return_str ;
?>
output:
A random new line
A random new line
A random new line
A random new line
A random new line