Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - how to create a newline character?

In PHP I am trying to create a newline character:

echo $clientid; echo ' '; echo $lastname; echo ' '; echo '\r\n'; 

Afterwards I open the created file in Notepad and it writes the newline literally:

1 John Doe\r\n 1 John Doe\r\n 1 John Doe\r\n

I have tried many variations of the \r\n, but none work. Why isn't the newline turning into a newline?

like image 259
davidjhp Avatar asked Nov 21 '10 14:11

davidjhp


People also ask

What is new line character in PHP?

It is a character in a string which represents a line break, which means that after this character, a new line will start. There are two basic new line characters: LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days.

Can you put \n in a string?

Adding Newline Characters 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 is the use of \r in PHP?

\r is a Carriage Return \n is a Line Feed (or new line). On Windows systems these together make a newline (i.e. every time you press the enter button your fix will get a \r\n ). In PHP if you open a Windows style text file you will get \r\n at the end of paragraphs / lines were you've hit enter.

What is Br in PHP?

Apart from nl2br() function, a html break line tag </br> is used to break the string. The </br> tag should be enclosed in double quotes, e.g., "</br>". For Example. To create the newline in PHP, let's see the number of examples.


1 Answers

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n" 

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break some text after'; 

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).

like image 181
Gumbo Avatar answered Sep 21 '22 07:09

Gumbo