我的html表单中有一个textarea,用户可以在其中输入数字,在表单提交后,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>
答案 0 :(得分: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
答案 1 :(得分: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 )
答案 2 :(得分: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;
答案 3 :(得分:0)
注意PHP_EOL is used to find the newline character in a cross-platform-compatible way
。我已经在windows / php 5.4.3中测试了你的代码,它的工作原理如上所述。当我运行你的小提琴,我得到错误。