Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using end of line in PHP echo string

Tags:

I am trying to write a PHP script that echos a string, but it doesn't recognize the end of line function in there.

For example,

echo "thank you \n " echo "for coming over" 

The \n is ignored and it prints the whole line as thank you for coming over.

I got the same result for the following to:

echo "thank you " . PHP_EOL.; echo "for coming over" . PHP_EOL.; 
like image 462
Ismael Avatar asked Jun 29 '11 11:06

Ismael


People also ask

Can we use \n in PHP?

?> Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

How do you end a line in a string?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What does nl2br mean in PHP?

The nl2br() is an inbuilt function in PHP and is used to insert HTML break tags in the place of all new lines in a string.

How do you break a line in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.


1 Answers

There are different ways to solve that:

Using Pre-formatted text

echo '<pre>'; // pre-formatted text, \n should work echo "thank you \n "; echo "for coming over"; echo '</pre>'; 

Changing the content type

header('Content-Type: text/plain'); echo "thank you \n "; echo "for coming over"; 

You browser will now properly read the output as text.

Using the HTML break element

echo "thank you <br>\n "; echo "for coming over"; 

So output always depends on what you want to output. Is it text? Is it HTML? Is it some text within HTML? Depending on what you need you should take care on the format and formatting.

like image 166
hakre Avatar answered Oct 31 '22 00:10

hakre