如何在PHP中convert 1/4 to 0.25
。
在表格中,我插入数字作为1/4
。action page
我得到的 post 变量为 1/4
.我怎样才能将其转换为0.25
.我认为在操作页面中,这是以字符串形式获得的。这就是为什么它显示为 1/4
.但我需要0.25.
我该怎么做??
主页
<input type="text" name="a" id="a">
操作页面
$a = $_POST['a'];
echo $a; //gives 1/4 but need 0.25
请帮忙..
一种可能的方法是:
在操作页面中,首先分解输入的值,如下所示:
$explode = explode('/', $_POST['a']);
然后你只需将它们划分:D
$result = $explode[0] / $explode[1];
echo $result; //echoes 0.25
L.E:在我看来,最好的方法是使用 3 个输入。一个带有第一个数字,一个带有操作,一个带有第二个数字。在这种情况下,您可以制作一个真正的计算器并在操作页面中执行正常操作,如下所示:
在显示页面中:
<input type="text" name="first_no" id="first_no">
<input type="text" name="operation" id="operation">
<input type="text" name="second_no" id="second_no">
在行动页面:
switch($_POST['operation']) {
case '+';
$result = $_POST['first_no'] + $_POST['second_no'];
break;
case '-';
$result = $_POST['first_no'] - $_POST['second_no'];
break;
case '*';
$result = $_POST['first_no'] * $_POST['second_no'];
break;
case '/';
$result = $_POST['first_no'] / $_POST['second_no'];
break;
//and so on... if you need more
}
echo $result;
L.E2:只是为了好玩,我只用 1 个输入为您的代码制作了一个版本
//get index
preg_match("/'D/is", $_POST['a'], $mList, PREG_OFFSET_CAPTURE);
$index = $mList[0][1];
//get operation
$operation = substr($string, $index, 1);
//get numbers
$explode = explode($operation, $string);
//produce result
switch($operation) {
case '+';
$result = $explode[0] + $explode[1];
break;
case '-';
$result = $explode[0] - $explode[1];
break;
case '*';
$result = $explode[0] * $explode[1];
break;
case '/';
$result = $explode[0] / $explode[1];
break;
//and so on... if you need more
}
echo $result;
希望这对:D有所帮助
您可以使用这样的函数:
<?php
function calculate_string( $mathString ) {
$mathString = trim($mathString);
$mathString = str_replace ('[^0-9'+-'*'/'(') ]', '', $mathString);
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
echo calculate_string("1/4");
?>
输出:
0.25
好吧,
你可以在这里使用eval,但要小心!直接将 $_POST 美元的东西解析到 eval 会使你的脚本对你的网络服务器非常危险,如果你没有正确转义输入!
如果你确定你会得到类似 1/4 或 1/2 的东西,这将做到这一点:
echo eval("return ".$_POST['a'].";");
但正如我所说。小心这个如果有人想要不好的东西,他可以在您的输入中输入exec('init 0')
,如果您的网络服务器获得执行此操作的权限,您的服务器将关闭(这只是不安全的 EVAL 的无数漏洞之一),所以我请您耐心等待。
第二种方法是拆分您的数字并划分它们。但这肯定会有很多格式问题。
问候