Bastien
Bastien

Reputation: 658

PHP - Echo new line character "\n" as single quote string

How can I echo the new line character \n 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\nbar

(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 :

Upvotes: 2

Views: 3375

Answers (5)

Rico_93
Rico_93

Reputation: 108

<?php
    $foo = 'foo';
    $nl = htmlspecialchars('\n');
    $bar = 'bar';

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

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94642

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 "\n" i.e. a newline control character sequence.

This would simply convert the "\n" to '\n'

<?php

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

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

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

RESULTS:

foo
bar

foo\nbar

EDIT:

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

$nl = str_replace("\n", '\n',getStringWithNewLineCharacter());

Upvotes: 2

Ben Hillier
Ben Hillier

Reputation: 2104

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

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

Upvotes: 0

arkascha
arkascha

Reputation: 42885

Just escape the backslash, that neutralizes its behavior:

echo "foo\\nbar";

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("\n", "\\n", $nl) . $bar;

Or obviously:

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

Upvotes: 1

J. Schwind
J. Schwind

Reputation: 21

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

Upvotes: 0

Related Questions