Home  >  Article  >  Backend Development  >  How to Achieve Cross-Platform Line Breaks in PHP?

How to Achieve Cross-Platform Line Breaks in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 01:59:02281browse

How to Achieve Cross-Platform Line Breaks in PHP?

Echoing Line Breaks Cross-Platform in PHP

In PHP, there are different approaches to outputting line breaks, namely n and r. While their usage varies depending on the operating system (OS), achieving a cross-platform compatible line break requires a different solution.

For this purpose, PHP offers the PHP_EOL constant. It automatically sets the appropriate line break based on the OS of the server hosting the PHP script. This ensures that the line break is rendered correctly regardless of the OS used by the user.

Here's an example of using PHP_EOL to echo a line break:

<code class="php">echo "Line 1" . PHP_EOL . "Line 2";</code>

Output:

Line 1
Line 2

For PHP versions prior to 5.0.2, you can implement the following code to define PHP_EOL manually:

<code class="php">if (!defined('PHP_EOL')) {
    switch (strtoupper(substr(PHP_OS, 0, 3))) {
        case 'WIN':
            define('PHP_EOL', "\r\n");
            break;
        case 'DAR':
            define('PHP_EOL', "\r");
            break;
        default:
            define('PHP_EOL', "\n");
    }
}</code>

The above is the detailed content of How to Achieve Cross-Platform Line Breaks in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn