PHP将字符串转换为int并计算

时间:2015-06-11 10:16:18

标签: php

我在两个变量中有两个值,即字符串

$var1 = "A$2800";
$var2 = "A$1500";               

我想要计算

$diff = $var1 - $var2;

应该{​​{1}}计算13002800的差异

5 个答案:

答案 0 :(得分:1)

您可以使用explode()

$var1 = explode("$", $var1); //$var1 is now an array containing: [0]=A, [1]=2800
$var2 = explode("$", $var2); //$var2 is now an array containing: [0]=A, [1]=1500

$diff = $var1[1] - $var2[1]; //$diff contains 1300

答案 1 :(得分:1)

如果字符串中的前缀始终为2个字符,请开始使用substr:

$val1 = substr("A$3000" , 2 , -2);

答案 2 :(得分:0)

您不能简单地将其添加到数字,首先您需要删除A$。例如。使用substr。

$var1 = "A$2800";
$var2 = "A$1500";

$num1 = (int)substr($var1, 2);
$num2 = (int)substr($var2, 2);

$diff = $num1 - $num2;

答案 3 :(得分:0)

您可以删除A$,然后计算 -

$var1 = "A$2800";
$var2 = "A$1500";
$var1 = str_replace("A$", '', $var1); //2800
$var2 = str_replace("A$", '', $var2); //1500

$diff = $var1 - $var2; //1300

答案 4 :(得分:0)

preg_replace('/\D/', '', $c)

以上内容应删除所有字符,仅保留数字。

$var1 = preg_replace('/\D/', '', "A$2800");
$var2 = preg_replace('/\D/', '', "A$1500");
$diff = $var1 - $var2;
echo $diff;

对于变量,只需修改第三个参数并插入变量即可。例如:

$var1 = preg_replace('/\D/', '', $var1);

:)