dave
dave

Reputation: 15499

PHP \n escape character

How come php process doesn't recongize the \n escape character in the string of this statement:

echo " testing \n testing2";

why?

Upvotes: 0

Views: 9972

Answers (7)

Dev Mostafa
Dev Mostafa

Reputation: 3

$teststring = ;
echo nl2br($teststring);

and type everything you want in $teststring

Upvotes: -1

alejandro
alejandro

Reputation: 11

Because your navigator think you want to display html whereas you want to display plain text. Just add a header explaining what type of content you want to display :

header('Content-Type: text/plain');
echo " testing \n testing2";

Upvotes: 1

AbiusX
AbiusX

Reputation: 2404

End of Line character means nothing in HTML, which is supposed to be PHP output.

The next line in HTML is <br/> tag, So you should output that :

echo "<br/>";

You can also change all occurrences of \n in a string to <br/> via nl2br function as noted by my friend.

Upvotes: 3

Czechnology
Czechnology

Reputation: 15012

It does, take a look in the source code. If you want to see it in the browser, use

echo nl2br(" testing \n testing2");

Browser ignores ignores excess whitespace (including a newline) and converts it to a space. You need HTML tags (e.g. <br />) to manually break lines.

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318778

When used in a HTML context, \n linebreaks will not be visible except in the HTML sourcecode as HTML uses <br /> for linebreaks. To convert them, use nl2br().

You also need to be careful how your string is quoted. Escape sequences like \n are only parsed in double-quoted "strings". In single-quoted 'strings' they are not parsed.

Upvotes: 3

Sam Starling
Sam Starling

Reputation: 5378

If you go to "View Source" in your browser, then you'll see that it has inserted a line break. However, in HTML, a line break is interpreted as whitespace and doesn't start a new line. As @Czechnology says, you want to use nl2br to replace the newlines with HTML line breaks (<br>).

Please also remember to accept the best answer when you ask a question.

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179264

I'm gonna go out on a limb here and guess that you wrote a page like this:

<?php

echo " testing \n testing2";

?>

And that the HTML output looks like:

testing testing2

Which is because HTML condenses white-space. You'll need to use some HTML elements to make the output look the way you think it should:

echo " testing <br /> testing2";

Upvotes: 5

Related Questions