PHP Echo Line Breaks

2019-01-04 01:18发布

What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?

EDIT: In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.

4条回答
对你真心纯属浪费
2楼-- · 2019-01-04 01:40
  • \n is a Linux/Unix line break.
  • \r is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix \n.
  • \r\n is a Windows line break.

I usually just use \n on our Linux systems and most Windows apps deal with it ok anyway.

查看更多
淡お忘
3楼-- · 2019-01-04 01:41

Jarod's answer contains the correct usage of \r \n on various OS's. Here's some history:

  • \r, or the ASCII character with decimal code 13, is named CR after "carriage return".
  • \n, or the ASCII character with decimal code 10, is named "newline", or LF after "line feed".

The terminology "carriage return" and "line feed" dates back to when teletypes were used instead of terminals with monitor and keyboard. With respect to teletypes or typewriters, "carriage return" meant moving the cursor and returning to the first column of text, while "line feed" meant rotating the roller to get onto the following line. At that time the distinction made sense. Today the combinations \n, \r, \r\n to represent the end of a line of text are completely arbitrary.

查看更多
Ridiculous、
4楼-- · 2019-01-04 01:42

No backwards compatibility necessary for PHP_EOL on PHP4.

Need to correct Moore's statement on constant PHP_EOL availability: "... is declared since PHP 5.0.2.".

No, it has been around since PHP 4.3.10. Anyone who is still running anything lesser than that should not be in biz anyhow. As of today no one should be using anything lesser than PHP 5!

From the PHP manual: "PHP_EOL The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2".

查看更多
贼婆χ
5楼-- · 2019-01-04 01:58

Use the PHP_EOL constant, which is automatically set to the correct line break for the operating system that the PHP script is running on.

Note that this constant is declared since PHP 5.0.2.

<?php
    echo "Line 1" . PHP_EOL . "Line 2";
?>

For backwards compatibility:

if (!defined('PHP_EOL')) {
    switch (strtoupper(substr(PHP_OS, 0, 3))) {
        // Windows
        case 'WIN':
            define('PHP_EOL', "\r\n");
            break;

        // Mac
        case 'DAR':
            define('PHP_EOL', "\r");
            break;

        // Unix
        default:
            define('PHP_EOL', "\n");
    }
}
查看更多
登录 后发表回答