0

我的 html 表单中有一个文本区域,用户可以在其中输入数字,在表单提交后,php 将回显数字的总和,例如,如果我输入

1
2

它会输出,

sum is 3

我的要求是,如果我在每组设备之间放置空格(一个或多个),则必须分别处理每组设备,例如,

1
2

3
4

及以上应显示输出为

sum is 3
sum is 7

但是使用下面的代码,我得到的输出如下

sum is 10

我的代码:

<html>
<body>

<div class="cal-main">
<form  id="form1" name="form1" action=" " method="post" > 

<div class="input">Enter Numbers</div>
<div class="output"><span><textarea class="textarea" name="numbers" ></textarea></span></div>


<div class="submit1">
    <input  id="first_submit" type="submit"  name="first_submit" value="first_submit" />
</div>

</form>


<?php

if (isset($_POST['first_submit']))
{
?>
<textarea onclick="this.select()" name="output_textarea" id="output_textarea" cols="100" rows="25" readonly value="">
<?php
$numbers = $_POST['numbers'];
$digits = explode(PHP_EOL.PHP_EOL, $numbers); // Favor PHP_EOL (end of line) to avoid cross OS issues
foreach($digits as $digit)
{

  $count = array_sum(explode(PHP_EOL, $digit));
  echo "sum is $count".PHP_EOL;
}
}
?>

</textarea>
</div>  
</body>
</html>

PHP 小提琴设置

4

4 回答 4

1

我会使用preg_split\r?\n

$digits = preg_split('#(\r?\n){2,}#',$numbers); //2 or more \r\n (\r optional)
foreach($digits as $key => $digit)
{

    $count = array_sum(preg_split('#\r?\n#', $digit));
    echo "sum is $count".PHP_EOL;
    if($key < count($digits)-1) echo '<br />';
}

输出:

sum is 3
sum is 7
于 2013-08-23T10:05:19.993 回答
0
$numbers = $_POST['numbers'];

$digits = explode("\n", $numbers); // explode by next line
$sums = array(); // array to put sums in
$i = 0;
foreach($digits as $digit) {
    $digit = trim($digit); // remove next line

    if(is_numeric($digit))
        $sums[$i] += $digit; // sum up
    else
        $i++; // next index (row wasn't number)
}

print_r($sums); 

// Output: Array ( [0] => 3 [1] => 7 )
于 2013-08-23T10:10:14.633 回答
0

使用 preg_split 更合适,尽管新行在不同的操作系统上可能不同。我的解决方案:

function split_new_lines($string){
    return preg_split('/\R/', $string);
}

$input = "
1
2

3
4

5
";

$lines = split_new_lines($input);

$sums = array();
$sum = null;
foreach($lines as $line){
    $line = trim($line);
    if(is_numeric($line))
    {
        if($sum === null)
            $sum = (int)$line;
        else
            $sum += (int)$line;
    }
    else
    {
        if($sum !== null)
            $sums[] = $sum;
        $sum = null;
    }
}
if($sum !== null)
    $sums[] = $sum;
于 2013-08-23T10:14:37.670 回答
0

请注意PHP_EOL is used to find the newline character in a cross-platform-compatible way。我已经在 windows/php 5.4.3 上测试了你的代码,它的工作原理如上所述。当我运行你的小提琴时,我得到了错误。

你的代码输出

于 2013-08-23T10:17:01.760 回答