PHP,SQL:仅存储来自用户输入的两个换行符

时间:2014-03-24 01:10:15

标签: php mysql

用户可以输入:

<textarea name="sometext"></textarea>

我想只存储最多两个换行符。例如:

纠正1(简单换行符):

This should be stored
This should be stored

纠正2:

This should be stored too

This should be stored too

错:

This should NOT be stored


This should NOT be stored

如果错误,应自动转换为示例2。

4 个答案:

答案 0 :(得分:2)

如果您只想计算换行符,可以使用substr_count()

if (substr_count($input, "\n") > 2) {
    echo 'Invalid input';
}

答案 1 :(得分:0)

似乎你想要避免多于一个空白行,在这种情况下,以下内容就足够了。

 $l1 = "This should be stored
 This should be stored";

 $l2 = "This should be stored too

 This should be stored too";

 $l3 = "This should NOT be stored


 This should NOT be stored";

 $expected_l3 = "This should NOT be stored

 This should NOT be stored";


 $examples = array($l1, $l2, $l3);
 $results = array();

 foreach ($examples as $example) {
   $lines = explode("\n", $example);
   $result = array();
   $blankLine = False;
   foreach ($lines as $ii => $line) {
     $line = trim($line);

     if ($blankLine and !$line) {
       continue;
     }
     $blankLine = False;

     $result[] = $line;

     if (!$line) {
       $blankLine = True;
     } 
   }

   $results[] = implode("\n", $result);
 }

 assert($results[0] == $l1);
 assert($results[1] == $l2);
 assert($results[2] == $expected_l3);

答案 2 :(得分:0)

你说你想为每个字符串存储最多2个新行。所以我们需要将此字符串除以\n次出现次数。

$data = "This should be stored too\nThis should be stored too";

$lines = preg_split("/\n/", $data);

var_dump($lines);


$data2 = "This should NOT be stored\n\n\nThis should NOT be stored";


$lines = preg_split("/\n/", $data2);

var_dump($lines);

$newlines = 0;
for($i = 0; $i < count($lines); $i++) {
    if($lines[$i] == '') {
        $newlines++;
    }
}

if($newlines > 2) {
    // do the conersion here.
}

答案 3 :(得分:0)

我认为@Anonymous几乎拥有它。如果我明白你在寻找什么,它似乎应该像下面这样。

if(substr_count($input,"\n\n\n")>0){
     $input=str_replace("\n\n\n","\n\n",$input); 
}

这将查找两个换行符,如果发现它们将删除它们。