How To Insert a Carriage Return in a PHP String

If you need to insert a Carriage Return in a string in PHP:

  • Carriage return is: "\r" 
  • But carriage return (CR) is different from "new line" (NL)
  • New Line (NL) is "\n"
  • What in HTML is called "line break" is the sum of a CR and a NL.
  • And different systems use this characters in different way; so, to get a "line break":
    • in Linux/Unix: \n
    • in Windows: \r\n
    • in Mac (pre-OS X): \r
    • in Max (OS X): \n (like Linux/Unix)

So, the best fix is to insert "\r\n"

the string "This is the first line\r\nThis is the second line"
Will render so:

This is the first line
This is the second line

You can also use the PHP constant PHP_EOL; so, the construct

"This is the first line".PHP_EOL."This is the second line"

will render the same.

Beware to the double quotes! "\r\n" will render a full carriage return; otherwise '\r\n' will render \r\n verbatim.

  • php
  • 9 Users Found This Useful
Was this answer helpful?

Related Articles

 How to Create a phpinfo page

The phpinfo() function outputs a huge amount of information about the system you're using, such...

 PHP Simple Contact Form Script

This is a sample script to insert a generic contact form in your website.You can easily modify...

 How To Make a Redirect in PHP

If you want that a page redirects automatically the user to a certain page or site (let's say,...

 How To Configure Easy WP SMTP Plugin To Use Gmail SMTP Service

Easy WP SMTP is a popular and free plugin for WordPress to send email(s) by an authenticated SMTP...

 Common Credit Card Transaction Response Code

In return of a credit card transaction, there will returned a 2-digit response code which is...