In PHP, sometimes we need to filter the line breaks of strings, such as the description information on the article page in the Tianya PHP blog. I directly cut the article content and filter out the html symbols, finally, we need to filter out the replications.
In PHP, sometimes we need to filter the line breaks of strings, such as the description information on the article page in the Tianya PHP blog. I directly cut the article content and filter out the html symbols, finally, we need to filter out the line breaks.
Below are some common methods to remove line breaks and PHP code. In fact, Tianya [phpha.com] wants to recommend a system constant [PHP_EOL].
- // 1st writing methods:
- Str_replace ("\ n", '', $ str );
- ?>
- // 2nd writing methods:
- Str_replace ("\ r \ n", '', $ str );
- ?>
- // 3rd writing methods:
- Preg_replace ("/\ s/", '', $ str );
- ?>
The following is a description:
First, let's talk about \ n, \ r, \ t
\ N soft carriage return:
In Windows, line breaks are displayed and returned to the beginning of the next line.
In Linux/unix, it only indicates line breaks, but does not return to the starting position of the next line.
\ R soft space:
In Linux/unix, return to the starting position of the row
In Mac OS, line breaks are displayed and returned to the start position of the next line, which is equivalent to \ n in Windows.
\ T hop (move to the next column)
Note:
They are valid in double quotes or delimiters, and are invalid in single quotes.
\ R \ n is generally used together to represent the carriage return key (in Linux and Unix) on the keyboard. \ n (in Windwos) can also be used only, and \ r is used to represent the carriage return in Mac OS!
\ T indicates the TAB key on the keyboard
Line Feed characters in the file:
Windows: \ n
Linux/unix: \ r \ n
The following code demonstrates three common methods for removing line breaks from strings in PHP:
- // 1) use the escape character function
- $ Str = str_replace (array ("/r/n", "/r", "/n"), '', $ str );
- ?>
- // 2) replace with a regular expression
- $ Str = preg_replace ('// s */', '', $ str );
- ?>
- // 3) use the PHP System constant [recommended]
- $ Str = str_replace (PHP_EOL, '', $ str );
- ?>