【发布时间】:2016-07-11 09:25:54
【问题描述】:
我正在尝试建立一个网站,人们可以在其中编写并将其发布到数据库中。文本是用<textarea> 编写的,我想保留空格作为格式。
例如,用户必须按ENTER 才能从他们正在输入的当前行进入一个新行,之后,如果他们想再次按ENTER 而不写任何内容,这意味着将有两个新行,我想将两个或两个以上的新行限制为一个空行。
Stack Overflow 有这个功能,写这行的时候,我从最后一行按了三次回车,但是你只能看到一个空格。
如何使用 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>
【问题讨论】:
-
您想在人们在文本区域中输入时阻止它,或者只是在提交表单后清理多行空白?
-
我想在提交后清理多行换行符。
-
这个答案应该会有所帮助:stackoverflow.com/questions/4052792
-
@mark.hch 还是不行。
-
这不起作用不是有用的信息。您应该发布来自 `$_POST['ab']` 的确切传入数据,并给出该特定输入所需输出的示例。请编辑您的问题以添加此信息。