PHP Echo Line Breaks

北战南征 提交于 2019-12-17 03:36:07

问题


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.


回答1:


  • \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.




回答2:


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");
    }
}



回答3:


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.




回答4:


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".



来源:https://stackoverflow.com/questions/255511/php-echo-line-breaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!