在PHP中,我如何折叠heredoc(文档内字符串)中的换行符?

3

针对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.

有什么想法吗?


当前结论(2018/01/17)

禁用默认的换行,使用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;
3个回答

1
个人而言,我会使用类似于{nbr}的东西,因为%%似乎过于通用,其中{nbr}表示“不换行”,{...}在模板中很常见。这只是一种观点。
但我也会使用正则表达式而不是str_replace。
preg_replace('/{nbr}[\r\n]+/', '', $str);

这样就可以匹配\r\r\n\n,甚至是\n\n或旧版Mac、Windows、Linux和多行结束符号。

您可以在这里查看:


因为 "%%" 似乎太通用了。确实如此。以前它是 "%BR%",但在某个时候有人改变了整个规范,可能是因为他/她懒得打字。这就是我感到不舒服的原因。 :_( - KEINOS

1
你可以采用破坏HTML标准的方式,使用<br>标签来表示需要换行。这对于习惯于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来使用正确的当前编码的换行符/换行或任何组合,平台可能有所不同。

对于习惯于HTML的人来说,这会感觉更直观。我明白了,首先删除所有换行符,然后将BR标签替换为换行符。这是个聪明的主意,也很直观!那么就没有撤消换行的转义码了吗? - KEINOS

0

这是我如何在heredoc中添加\n的方法

<?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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接