php removes string newline examples to share

  • 2021-01-06 00:29:21
  • OfStack

The first way of writing:


<?php
str_replace("n", '', $str); 
?>

The second way of writing:


<?php
str_replace("rn", '', $str); 
?>

The third way of writing:


<?php
preg_replace("/s/", '', $str); 
?>

Relevant explanations are as follows:
Let's start with n,r,t
n Soft Enter:
In Windows represents a newline and returns to the beginning of the next line
In Linux/unix, only a newline is represented, but it does not return to the start of the next line
r Soft Space:
In Linux/unix means return to the beginning of the current row
In Mac OS represents a newline and returns to the beginning of the next line, equivalent to n in Windows
t skip (move to the next column)
Additional Notes:
They are valid in strings denoted by double quotes or delimiters and not in strings denoted by single quotes.
rn 1 type 1, used to represent the enter key on the keyboard (Linux,Unix), also can only use n(Windwos), Mac OS in r to represent the enter key!
t represents the TAB key on the keyboard
A newline symbol in a file:
windows: n
linux/unix: rn

The following code illustrates three common ways to remove newlines from strings in PHP

1. Use the escape character function


<?php
$str = str_replace(array("/r/n", "/r", "/n"), '', $str);
?>

2. Use regular expression substitutions


<?php
$str = preg_replace('//s*/', '', $str);
?>

3. PHP system constants are recommended


<?php
$str = str_replace(PHP_EOL, '', $str);
?> 


Related articles: