Home >Backend Development >PHP Problem >How to remove newline character from string in php
php method to remove line breaks in strings: 1. Use the "str_replace("n", '', $str);" method to remove line breaks; 2. Use "str_replace("rn", '', $str);" method to remove newlines; 3. Remove newlines through preg_replace.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer.
How to remove line breaks in strings in PHP
In PHP, sometimes we need to filter line breaks in strings, such as the article in Tianya PHP Blog For the description information of the page, I directly intercepted the article content, filtered out the HTML symbols, and finally filtered out the line breaks.
The following is a summary of common methods and PHP codes for removing line breaks. In fact, what Tianya wants to recommend to everyone is a system constant [PHP_EOL].
// 第1种写法: <?php str_replace("n", '', $str); ?> // 第2种写法: <?php str_replace("rn", '', $str); ?> // 第3种写法: <?php preg_replace("/s/", '', $str); ?>
The following is the relevant explanation:
First let’s talk about n,r,t
n Soft Enter:
In In Windows, it means a line break and returns to the beginning of the next line.
In Linux/unix, it only means a line break, but does not return to the beginning of the next line.
r Soft space:
In Linux/unix, it means returning to the beginning of the current line
In Mac OS, it means wrapping and returning to the beginning of the next line, which is equivalent to the effect of n in Windows
t Tab (move to the next column)
Supplementary notes:
They are valid in strings represented by double quotes or delimiters, and in strings represented by single quotes invalid.
rn are generally used together to represent the Enter key on the keyboard (in Linux and Unix). You can also just use n (in Windows). In Mac OS, use r to represent Enter!
t represents the TAB key on the keyboard
The newline symbol in the file:
windows: n linux/unix: rn
[Recommended learning: PHP video tutorial]
The following uses code to illustrate three common methods of removing line breaks in strings in PHP
// 1)使用转义字符函数 <?php $str = str_replace(array("/r/n", "/r", "/n"), '', $str); ?> // 2)使用正则表达式替换 <?php $str = preg_replace('//s*/', '', $str); ?> // 3)使用PHP系统常量【推荐】 $str = str_replace(PHP_EOL, '', $str); ?>
The above is the detailed content of How to remove newline character from string in php. For more information, please follow other related articles on the PHP Chinese website!