开发者

Allowing at most 2 newline in textarea

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 = p开发者_开发技巧reg_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>


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:

$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.

:)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜