PHP - 将新行字符“ ”作为单引号字符串进行回显

How can I echo the new line character as if it was in a single quote string?

$foo = 'foo';
$nl = getStringWithNewLineCharacter();
$bar = 'bar';

echo $foo . $nl . $bar;

will output :

foo
bar

What I want is :

foo
bar

(Obviously, I do not control the return value of the getStringWithNewLineCharacter() function.)

Or said differently, how can I force a variable to be interpreted as a single quote string?


EDIT

While answers provided gave a workaround, the real question here is how to interpret a double quoted string variable as a single quoted string variable. Maybe it's not possible, I don't know. To answer this, it requires understanding of how the interpreter manages string variables (which I lack).

So :

  • How is the "quote type" of a string defined?
  • Is it immutable?
  • Is there a way to change how the interpreter will manage a string variable?

you have to use the ', not the "', like this echo ' ' not echo " "

Just escape the backslash, that neutralizes its behavior:

echo "foo\
bar";

You can write that in a literal manner as above or in a string replacement command, whatever. The outcome is the same: the literal characters \ and n next to each other instead of the line feed character:

echo $foo . str_replace("
", "\
", $nl) . $bar;

Or obviously:

echo $foo . str_replace("
", '
', $nl) . $bar;

Once the " " character is in the variable, it's already converted to newline. You will need to convert it back.

$nl = preg_replace("#
#", '
', $nl);

Not totally sure this is what you want but here goes anyway.

I think you are saying that you have no control over the returned value of getStringWithNewLineCharacter(); and you think it is returning " " i.e. a newline control character sequence.

This would simply convert the " " to ' '

<?php

$foo = 'foo';
$nl = "
";
$bar = 'bar';

echo $foo . $nl . $bar;   // 2 lines
echo PHP_EOL;

$nl = str_replace("
", '
', $nl);
echo $foo . $nl . $bar;   // one line
echo PHP_EOL;

RESULTS:

foo
bar

foo
bar

EDIT:

Or if you want to make it permanent at least for the duration of this script do :-

$nl = str_replace("
", '
',getStringWithNewLineCharacter());
<?php
    $foo = 'foo';
    $nl = htmlspecialchars('
');
    $bar = 'bar';

    echo $foo . $nl . $bar;
?>