Home >Backend Development >PHP Problem >How to replace newline characters in php
How to replace newlines in php: 1. Use the "str_replace" function that comes with php to replace newlines; 2. Use regular expressions to replace newlines; 3. Use variables defined by php to Implement replacement line breaks.
Recommendation: "PHP Tutorial"
PHP replace newline character
First type:
The code is as follows:
<?php ?$str="this is a test \n"; $patten = array("\r\n", "\n", "\r"); ?//先替换掉\r\n,然后是否存在\n,最后替换\r $str=str_replace($order, "", $str); ?> //php 有三种方法来解决 //1、使用str_replace 来替换换行 $str = str_replace(array("\r\n", "\r", "\n"), "", $str); //2、使用正则替换 $str = preg_replace('//s*/', '', $str); //3、使用php定义好的变量 (建议使用) $str = str_replace(PHP_EOL, '', $str);
The code is as follows:
/* * 获得用户操作系统的换行符,\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';//权重大一点 } return $the_crlf; }
Note: When displaying the front page, use nl2br The newline becomes 0c6dc11e160d3b678d68754cc175188a
Second example description:
I found 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 newline character Okay
But in fact it is not possible!
I’m very depressed. I tried many times but it just doesn’t work.
Finally changed to this
The code is as follows:
$text=str_replace("\n","",$text); $text=str_replace("\r","",$text); $text=str_replace("\r\n","",$text);
Everything is OK~~It turns out to be a problem of double quotes and single quotes! !
Double quotation marks are less efficient than single quotation marks, because when double quotation marks are parsed by PHP, they will also judge whether there are variables in them, but single quotation marks will not make this judgment, so generally speaking, there is no Whenever variables are involved, I always use single quotes. I didn’t expect that replacing the newline character this time would not work with single quotes...
Finally written in one sentence
The code is as follows:
$order = array("\r\n", "\n", "\r"); $replace = ''; $text=str_replace($order, $replace, $text);
This will replace the newline character!
The above is the detailed content of How to replace newline characters in php. For more information, please follow other related articles on the PHP Chinese website!