Three ways to replace carriage return and line feed characters in PHP

angryTom
Release: 2023-04-07 16:52:01
forward
5607 people have browsed it

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.

The following introduces 3 methods of replacing carriage return and line feed in PHP.

Note that the last one is the best and most convenient~~~

Method 1: Regular expression method

$str = preg_replace('/\s*/', '', $str);
Copy after login

This method is the least efficient.

Method 2: Built-in function method

$str = str_replace(array("\r", "\n", "\r\n"), '', $str);
Copy after login

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);
Copy after login

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!

Related labels:
source:www.awaimai.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template