<?php
$text = $_POST['oviliz'];
$replaces = array(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => '4',
'e' => '5',
);
for( $i=0,$l=strlen($text);$i<$l;$i++ ){
if( isset($replaces[$text[$i]]) ){
$text[$i] = $replaces[$text[$i]];
}
}
?>
<form action="" method="post">
<p>My input text: <input name="oviliz" type="text"/><input class="button" type="submit" name="submit" value="Submit"/></p>
</form>
<?php
echo "Numbers: ".$text;
$sum = 0;
$sum += array_sum(str_split($text));
echo "= " .$sum;
?>
我想总结被替换的结果。在我的例子中,如果我输入“abc”,结果将是“123”。我想总结“1 + 2 + 3”并获得6的结果。
修改
感谢Rizier123,我已使用$sum += $text;
$sum += array_sum(str_split($text));
我现在正在寻找如何在第一次替换结果后仅根据请求打印它。
答案 0 :(得分:1)
要获得输入的总和,请使用:
$sum += array_sum(str_split($text));
要仅在按下提交按钮时打印它,只需进行如下基本检查:
<form action="" method="post">
<p>My input text: <input name="oviliz" type="text"/><input class="button" type="submit" name="submit" value="Submit"/></p>
</form>
<?php
if(isset($_POST["submit"])) {
//^^^^^ Check's if the submit button is pressed
$text = $_POST['oviliz'];
$replaces = array(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => '4',
'e' => '5',
);
for( $i=0,$l=strlen($text);$i<$l;$i++ ){
if( isset($replaces[$text[$i]]) ){
$text[$i] = $replaces[$text[$i]];
}
}
echo "Numbers: ".$text;
$sum = 0;
$sum += array_sum(str_split($text));
echo "= " .$sum;
}
?>
答案 1 :(得分:0)
冒着完成家庭作业的风险:
$sum = array_sum(
array_intersect_key($replaces, array_flip(str_split($_POST['oviliz'])))
);
答案 2 :(得分:0)
我会这样做:
$input = $_POST['oviliz'];
$replaces = array(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => '4',
'e' => '5',
);
$letters = str_split($input);
foreach($letters as $letter){
$total += $replaces[$letter];
}
?>
<form action="" method="post">
<p>My input text: <input name="oviliz" type="text"/><input class="button" type="submit" name="submit" value="Submit"/></p>
</form>
<?php
echo "Numbers: " . $input;
echo "= " . $total;
?>