Several methods to replace line breaks in PHP. For more information, see
First:
Copy codeThe code is as follows:
? $ Str = "this is a test \ n ";
$ Patten = array ("\ r \ n", "\ n", "\ r ");
? // Replace \ r \ n first, check whether \ n exists, and finally replace \ r
$ Str = str_replace ($ order, "", $ str );
?>
// Php has three solutions
// 1. use str_replace to replace the line feed.
$ Str = str_replace (array ("\ r \ n", "\ r", "\ n"), "", $ str );
// 2. use regular expression replacement
$ Str = preg_replace ('// s */', '', $ str );
// 3. use the variables defined in php (recommended)
$ Str = str_replace (PHP_EOL, '', $ str );
Copy codeThe code is as follows:
/*
* Get the line break of the user's operating system, \ n
* @ Access public
* @ Return string
*/
Function get_crlf ()
{
If (stristr ($ _ SERVER ['http _ USER_AGENT '], 'win '))
{
$ The_crlf = '\ r \ n ';
}
Elseif (stristr ($ _ SERVER ['http _ USER_AGENT '], 'Mac '))
{
$ The_crlf = '\ r'; // for old MAC OS
}
Else
{
$ The_crlf = '\ n'; // The weight is larger.
}
Return $ the_crlf;
}
Note: Use nl2br to change the line feed
Example 2:
Find an interesting thing:
$ Text = "aaaa
Ccc ";
$ Text = str_replace ('\ n', "", $ text );
$ Text = str_replace ('\ r', "", $ text );
$ Text = str_replace ('\ r \ n', "", $ text );
Normally, the above code should be able to replace the line break.
But in fact it is not!
Very depressed. I tried it many times, but it didn't work.
Finally, change it to this
Copy codeThe code is as follows:
$ Text = str_replace ("\ n", "", $ text );
$ Text = str_replace ("\ r", "", $ text );
$ Text = str_replace ("\ r \ n", "", $ text );
Everything is okay ~~, It turns out to be double quotation marks. single quotation marks are a problem !!
Double quotation marks are less efficient than single quotation marks, because during the process of being parsed by php, double quotation marks will also determine whether there is a variable in it, and single quotation marks won't have this judgment, so generally speaking, without variables involved, I would always use single quotes. I didn't expect this time to replace line breaks, but it wouldn't work if I used single quotes ·····
Last sentence
Copy codeThe code is as follows:
$ Order = array ("\ r \ n", "\ n", "\ r ");
$ Replace = '';
$ Text = str_replace ($ order, $ replace, $ text );
This will replace the line break!