Home > Backend Development > PHP Problem > How to replace newline characters in php

How to replace newline characters in php

(*-*)浩
Release: 2023-02-26 11:52:01
Original
2282 people have browsed it

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

This method is the least efficient.

Method 2: Built-in function method

//使用str_replace 来替换换行 
$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 How to replace newline characters in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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