我正在尝试构建一个网站,让人们可以在其中编写并将其发布到数据库中。文本是在 <textarea>
中编写的,我希望保留空格作为格式。
例如,用户必须按下 ENTER
才能从他们正在输入的当前行跳转到新行,在此之后,如果他们想通过什么都不写来再次按下 ENTER
,那么就意味着会有两个换行符,我想将两个或多个换行符限制为只有一个空行。
Stack Overflow 有这个功能,当我写这行代码时,我从上一行按了三次 enter ,但您只能看到一个空格。
我如何用 PHP 实现这一点? 我已经尝试过 nl2br()
,但它似乎会将每个 \n
更改为 <br \>
。 我该如何解决这个问题?
实际源代码:
<!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>
这是输出的HTML源代码:
<!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>
看看由 nl2br
创建的 <br />
,我希望连续的 <br /r>
变成 <p>...</p>
。
这是我想要的输出 HTML 源代码:
<!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>
rtrim($textarea);
会移除文本框中的尾部空格。 - Ryan Vincent