Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP how can I collapse the line breaks inside heredoc (here document)?

For CLI purpose, I want to partly collapse (ignore line break) inside the heredoc(here document).

Currently, I use %% at the end of the lines which I want to collapse then replace them using str_replace("%%\n",'', $string);. But I don't feel quite comfortable with it.

Is there any escape cord or smarter ways to do so?

For example:

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

I get as below:

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.

Any ideas?


Current conclusion (2018/01/17)

Disable line breaks as a default behavior, and use BR tags to line break instead.
1. Replace PHP_EOL(line breaks) to ''(blank).
2. Replace the BR tags to PHP_EOL.

Sample code:

<?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;
like image 479
KEINOS Avatar asked Nov 28 '25 18:11

KEINOS


1 Answers

You could resort to mangling the HTML standard of using <br> tags to say when you do want a line break. This will feel more intuitive for people used to 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;

Note the use of PHP_EOL to use the correct current encoding of a new line/line break or whatever combination the platform your using has.

like image 114
Nigel Ren Avatar answered Nov 30 '25 08:11

Nigel Ren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!