Allowing at most 2 newline in textarea

故事扮演 提交于 2020-01-06 04:50:28

问题


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>

回答1:


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.




回答2:


Try this:

$data = "whatever data with \r\n\r\n\r\n more than \r\n two lines \r\n\r\n example";
$fixed_data = preg_replace( "\r\n\r\n([\r\n]+)", "\r\n\r\n", $data);
echo $fixed_data;
// should output: whatever data with \r\n\r\n more than \r\n two lines \r\n\r\n example

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.

:)




回答3:


$data = preg_replace('/(\r?\n){3,}/',"\n\n",$data);


来源:https://stackoverflow.com/questions/6475592/allowing-at-most-2-newline-in-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!