The php method for removing newlines summarizes the use of the of PHP_EOL variable

  • 2020-05-30 19:40:54
  • OfStack

A small line feed, in fact, in different platforms have different implementation, why so, can be the world is diverse. Instead of using /n for line feed in the unix world, windows USES /r/n to reflect its differences, and more interestingly, /r in mac. Therefore, the unix series USES /n, windows series USES /r/n, mac series USES /r, so there is a lot of trouble in using the programs you write to run on different platforms. Here are some common ways PHP can remove line breaks.

The first way to write:

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


The second way:

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

The third way:


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

About the \ n \ r \ t
\n soft carriage return: in Windows, means a new line and returns to the beginning of the next line; in Linux, unix, means only a new line, but does not return to the beginning of the next line.
\r soft space: in Linux, unix means to return to the beginning of the row in question. In Mac OS represents a newline and returns to the beginning of the next line, equivalent to the effect of \n in Windows.
\t skip (move to the next column)

Some notes:

They are valid in strings represented by double quotation marks or delimiters, and not in strings represented by single quotation marks.
\r\n 1, or \n(Windwos), \r (Mac OS), for the return key on the keyboard (Linux,Unix).
\t represents the "TAB" key on the keyboard.
Newline symbols in file: windows: \n, linux,unix: \r\n

Supplementary code:


<?php 
//php  Line feeds for different systems  
// The implementation of line feeds between different systems is not 1 The sample of  
//linux  with unix using  /n 
//MAC  with  /r 
//window  In order to embody linux different   It is  /r/n 
// So on different platforms   The implementation method is not 1 sample  
//php  There are 3 Here's a way to do it  
//1 , the use of str_replace  So let's replace the newline  
$str = str_replace(array("/r/n", "/r", "/n"), "", $str); 
//2 , using regular substitution  
$str = preg_replace('//s*/', '', $str); 
//3 , the use of php Defined variable   (recommended)  
$str = str_replace(PHP_EOL, '', $str); 
?> 

PHP_EOL is a defined variable that represents the newline character of php. This variable will change according to the platform. Under windows it will be /r/n, under linux it will be /n, under mac it will be /r.
$str = str_replace(PHP_EOL, '', $str); 


Related articles: