Home > Article > Backend Development > Replace line feed and carriage return in form input box in php_PHP tutorial
A summary of some methods for replacing line feeds and carriage returns in form input boxes in PHP. Friends in need can refer to this article.
The code is as follows | Copy code | ||||||||
?$str="this is a test n";
?> |
代码如下 | 复制代码 |
$content=empty($_POST['content'])?null:trim($_POST['content']); if(!empty($content))echo str_replace("r",'rl',nl2br($content)); echo "r".' ----------分割线----------------------'."r"; if(!empty($content))echo str_replace("n",'nl',nl2br($content)); echo "n".' ----------分割线----------------------'."n"; if(!empty($content))echo str_replace("r",'rl',str_replace("n",'nl',nl2br($content))); echo "r".' ----------分割线---------------------- '."n"; echo 'hello'."n".'boys!'; echo 'hello'."r".'boys!'; ?> |
The code is as follows | Copy code |
//1. Use str_replace to replace newlines $str = str_replace(array("rn", "r", "n"), "", $str); //2. Use regular replacement $str = preg_replace('//s*/', '', $str); //3. Use variables defined by php (recommended) $str = str_replace(PHP_EOL, '', $str); ?/* * Get the newline character of the user's operating system, n * @access public * @return string */ function get_crlf() { If (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) { $the_crlf = 'rn'; } elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) { $the_crlf = 'r'; // for old MAC OS } else { $the_crlf = 'n';//The weight is bigger } Return $the_crlf; } |
The code is as follows | Copy code |
----------Separating line----------------------'."n "; if(!empty($content))echo str_replace("r",'rl',str_replace("n",'nl',nl2br($content))); echo "r".' ----------Separating line---------------------- '."n"; echo 'hello'."n".'boys!'; echo 'hello'."r".'boys!'; ?> |
1. The PHP function nl2br() inserts an HTML newline character before each new line (rn) in the string:
;
2. The newline under Windows is (rn);
3. In Notepad, r or n have the function of line break;
Note: When the front page is displayed, use nl2br to change the line break to