文本区域中最多允许 2 个换行符
我想在文本区域中最多允许 2 个换行符。
我想要 PHP 或 PHP+JavaScript/jQuery 的解决方案。
当用户输入超过 2 个换行符时,它们将被替换为 2 个换行符。
输入:
0
1
2
3
4
无论我尝试过还是失败
<html>
<form name="f" method="post">
1 <textarea name="t">
<?php
if (isset($_POST['t']))
{
$t2 = $_POST['t'];
$t3 = $_POST['t'];
$t4 = $_POST['t'];
echo $_POST['t'];
}
?>
</textarea>
<br>
2 <textarea name="t2">
<?php
if (isset($_POST['t']))
{
$t2 = preg_replace('/\s*$^\s*/m', "\n", $t2);
echo preg_replace('/[ \t]+/', ' ', $t2);
}
?>
</textarea>
<br>
3 <textarea name="t3">
<?php
if (isset($_POST['t']))
{
$t3 = preg_replace("/[\n]+/m", "\n\n", $t3);
//$t3 = preg_replace("/[\r\n]+/m", "\n", $t3);
$t3 = preg_replace("/[\t]+/m", "\t", $t3);
$t3 = preg_replace("/[ ]+/m", " ", $t3);
//$t3 = preg_replace("/\s+/", ' ', $t3);
echo $t3;
}
?>
</textarea>
<br>
4 <textarea name="t4">
<?php
if (isset($_POST['t']))
{
//$t4 = preg_replace('/[\n\r]{2,}/', "\n\n", $t4);
$t4 = preg_replace( "\r\n\r\n([\r\n]+)", "\r\n\r\n", $t4);
echo $t4;
}
?>
</textarea>
<input type="submit">
</form>
</html>
I want to allow at most 2 newline characters in a text area.
I want this solution in PHP or in PHP+JavaScript/jQuery.
When ever the users enter more than 2 newline they will be replaced by 2 newline characters.
The Input:
0
1
2
3
4
whatever i tried and failed
<html>
<form name="f" method="post">
1 <textarea name="t">
<?php
if (isset($_POST['t']))
{
$t2 = $_POST['t'];
$t3 = $_POST['t'];
$t4 = $_POST['t'];
echo $_POST['t'];
}
?>
</textarea>
<br>
2 <textarea name="t2">
<?php
if (isset($_POST['t']))
{
$t2 = preg_replace('/\s*$^\s*/m', "\n", $t2);
echo preg_replace('/[ \t]+/', ' ', $t2);
}
?>
</textarea>
<br>
3 <textarea name="t3">
<?php
if (isset($_POST['t']))
{
$t3 = preg_replace("/[\n]+/m", "\n\n", $t3);
//$t3 = preg_replace("/[\r\n]+/m", "\n", $t3);
$t3 = preg_replace("/[\t]+/m", "\t", $t3);
$t3 = preg_replace("/[ ]+/m", " ", $t3);
//$t3 = preg_replace("/\s+/", ' ', $t3);
echo $t3;
}
?>
</textarea>
<br>
4 <textarea name="t4">
<?php
if (isset($_POST['t']))
{
//$t4 = preg_replace('/[\n\r]{2,}/', "\n\n", $t4);
$t4 = preg_replace( "\r\n\r\n([\r\n]+)", "\r\n\r\n", $t4);
echo $t4;
}
?>
</textarea>
<input type="submit">
</form>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需执行
$subject = preg_replace('/\n{2,}/', "\n\n", $subject);
这将捕获两个或多个换行符并将其替换为两个换行符。编辑
如果你想更安全,你可以将模式更改为
/[\n\r]{2,}/
来捕获回车符,但我认为这是不必要的。Just do
$subject = preg_replace('/\n{2,}/', "\n\n", $subject);
That will catch two or more newlines and replace it with two newlines.edit
If you wanted to be safer you might change the pattern to
/[\n\r]{2,}/
to catch carriage returns as well but I think it's unnecessary.试试这个:
上面的正则表达式替换应该查找两个新行(可选的无限多个新行)并将它们全部替换为两个新行。
:)
Try this:
The above regex replacement should look for two new lines (with an optional infinite as many new lines) and replace them all with 2 new lines.
:)