在textarea中最多允许2个换行符 [英] Allowing at most 2 newline in textarea
问题描述
我想在文本区域中最多允许2个换行符.
我想要在PHP或PHP + JavaScript/jQuery中使用此解决方案.
只要用户输入的换行符超过2个,他们就会被2个换行符替换.
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.
输入:
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>
推荐答案
只需执行$subject = preg_replace('/\n{2,}/', "\n\n", $subject);
即可捕获两个或多个换行符,并用两个换行符替换.
Just do $subject = preg_replace('/\n{2,}/', "\n\n", $subject);
That will catch two or more newlines and replace it with two newlines.
修改
如果您想更加安全,则可以将模式更改为/[\n\r]{2,}/
来捕获回车,但我认为这是不必要的.
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.
这篇关于在textarea中最多允许2个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!