Leo
Leo

Reputation: 5122

PHP how to convert \n to newline

How do I make a string that was declared using single quotes, evaluate \n as if it was declared using double quotes?

ie.

echo 'Line1\nLine2'; // Does not split.
echo "Line1\nLine2"; // It splits.

$s = 'A string declared using \n single quotes which I can\'t change...';
echo $s // I need this to have the split at \n

Upvotes: 4

Views: 4818

Answers (3)

Hudson Cantuária
Hudson Cantuária

Reputation: 51

Can you replace \' in ', using str_replace()

$s = 'A string declared using \n single quotes which I can\'t change...';
$s= str_replace('\n', "\n", $s);

or use following syntax

nl2br($s);

Upvotes: 2

Jonathan Gagne
Jonathan Gagne

Reputation: 4379

First you would have to repair your string. Put \' instead ', then you would have to use str_replace()

$s = 'A string declared using \n single quotes which I can\'t change...';
$s= str_replace('\n', "\n", $s);

Upvotes: 2

iainn
iainn

Reputation: 17417

You should just be able to str_replace them to an actual newline:

$s = str_replace('\n', "\n", $s);

See https://3v4l.org/j0etV

If you're going to be displaying this as HTML, note that you'll also need to run it through nl2br (or if you're using a templating engine this might already be done for you)

Upvotes: 8

Related Questions