Home > Article > Backend Development > Three ways to replace carriage return and line feed characters in PHP
The small carriage return and line feed have different implementations on different platforms.
Why is this? The world is diverse!
Recommended learning: PHP video tutorial
Originally, In the Unix/Linux world, \n is used for line breaks.
In order to reflect the difference, Windows uses \r\n.
What’s more interesting is that Mac also uses \r.
Therefore, the program needs to perform different processing to replace the carriage return and line feed characters on different platforms.
Note that the last one is the best and most convenient~~~
Method 1: Regular expression method
$str = preg_replace('/\s*/', '', $str);
This method is the least efficient.
Method 2: Built-in function method
$str = str_replace(array("\r", "\n", "\r\n"), '', $str);
This method is the second most efficient, but the writing method is slightly longer.
Method 3: PHP_EOL method
I have to re-look at PHP’s predefined constants,
PHP_EOL is one of them, representing PHP Newline character,
, this constant will vary according to different platforms. Under Windows, it is \r\n, under Linux, it is \n, and under Mac, it is \r
. Therefore, the best method is That’s it:
$str = str_replace(PHP_EOL, '', $str);
The above is the detailed content of Three ways to replace carriage return and line feed characters in PHP. For more information, please follow other related articles on the PHP Chinese website!