Home  >  Article  >  Backend Development  >  How to replace newline characters in php

How to replace newline characters in php

(*-*)浩
(*-*)浩Original
2019-10-12 09:52:472096browse

How to replace newline 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 \r is used again.

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

This method is the least efficient.

Method 2: Built-in function method

//使用str_replace 来替换换行 
$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 How to replace newline characters 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