I am trying to build an site where people write and post it to the database. The text is written in <textarea>
and I want to preserve the whitespaces as formatting.
For example, users have to press ENTER
to get to a new line from the current one they were typing on, after that, if they want to press ENTER
again by writing nothing, that means there will be two new lines, I want to keep the two or more than two new lines restricted to just one blank line.
Stack Overflow has this feature, while writing this line, I pressed enter thrice from the last line, but you can only see one white space.
How do I achieve this with PHP? I have tried nl2br()
but that seems to change every \n
to <br \>
. How do I solve this issue?
The actual source code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post">
<textarea name="ab">
</textarea>
<button>Sub</button></form>
<?php
$post= preg_replace('/\n+/', "\n", $_POST['ab']);
echo nl2br($post);
//echo str_replace($find,$replace,$post);
?>
</body>
</html>
This is the output html source:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post">
<textarea name="ab">
</textarea>
<button>Sub</button></form>
This is a single line.<br />
now I pressed enter,<br />
<br />
<br />
three spaces below (should show only 1 whitespace)</body>
</html>
Look at the <br />
created by the nl2br
, I want the consecutive <br /r>
to be <p>...</p>
.
This is what I want to be the output html source:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post">
<textarea name="ab">
</textarea>
<button>Sub</button></form>
This is a single line.<br />
now I pressed enter,<br />
<p>
three spaces below (should show only 1 whitespace)</p></body>
</html>