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

How to remove newline characters in php

藏色散人
藏色散人Original
2020-09-02 10:30:404020browse

How to remove line breaks in php: 1. Use [tr_replace("\n","",$content);] to remove line breaks; 2. Use [str_replace("\r\n", "",$str);] method to remove newline characters; 3. Remove newline characters through regular expressions.

How to remove newline characters in php

Recommended: "PHP Video Tutorial"

A small Line breaks actually have different implementations on different platforms. Why is this necessary? The world is diverse. Originally, /n was used to replace line breaks in the Unix world, but in order to reflect the difference, Windows uses /r/n. What is more interesting is that /r is used in Mac. Therefore, the Unix series uses /n, the Windows series uses /r/n, and the Mac uses /r. This will cause a lot of trouble for the program you write to run on different platforms. Here are some common ways to remove newlines in PHP.

The first way of writing:

$content=str_replace("\n","",$content);
echo $content;

The second way of writing:

str_replace("\r\n","",$str);

The third way of writing:

$content=preg_replace("/\s/","",$content);
echo $content;

About\n,\r,\ t
\n Soft return: In Windows, it means a line break and returns to the beginning of the next line. In Linux and Unix, it only means a line break, but it does not return to the beginning of the next line.
\r Soft space: In Linux and Unix, it means returning to the beginning of the current line. In Mac OS, it means breaking a line and returning to the beginning of the next line, which is equivalent to the effect of \n in Windows.
\t Tab (move to next column)

A few notes:

They are valid in strings represented by double quotes or delimiters, Invalid in single quoted strings.
\r\n is generally used together to represent the Enter key on the keyboard (in Linux and Unix). You can also just use \n (in Windwos). In Mac OS, use \r to represent Enter.
\tIndicates the "TAB" key on the keyboard.
Newline symbols in the file: windows: \n, linux, unix: \r\n

Supplementary code:

PHP_EOL is a defined variable, representing php The newline character, this variable will change according to the platform. It will be /r/n under windows, /n under linux, and /r under mac. Just press the following to change the newline.

$str = str_replace(PHP_EOL, '', $str);

Regular replacement:

 preg_replace("/(^[\s]+|[\s]+$|  )/", '', $str);

The above is the detailed content of How to remove 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